Shahrzad A Shahrzad A - 7 months ago 36
Node.js Question

display an embedded document data model in mongoose in browser

I'm using embedded document data model in mongoose and my data is like this

var firstuser1 = new user({userid: 'absj8d55',
tokenid: 'akn178i3',
media: [{mediaid: 'mid01',mediaurl: 'dl.ingrm.com/mid01'},{mediaid: 'mid03', mediaurl: 'dl.ingrm.com/mid03'}]
});


I save it and then I want to display it on my browser so I use this function:

app.get('/allmedia', function(req, res) {
user.find({},function(err, myuser) {
res.send(myuser);
//console.log(myuser);
})});


User is my model here:

var userschema = new mongoose.Schema({
userid: {type: String, unique: true},
tokenid: {type: String, sparse: true, default: null}},{
media: {
mediaid: String,
mediaurl: String
}
});
var user = mongoose.model('mydb', userschema);


U run this code but all I get is this:


[{"_id":"5780e1e5797fc3181865686b","userid":"absd1234","tokenid":"akdndkdn12345678"}


It doesn't display the media!!

Where am i doing wrong?

Thanks.

Answer

In userschema constructor, you are setting media object as the second argument. Second argument in schema constructor is options object. Change this:

var userschema = new mongoose.Schema({
  userid: {type: String, unique: true},
  tokenid: {type: String, sparse: true, default: null}
},{
  media: {
    mediaid: String,
    mediaurl: String
  }
})

to:

var userschema = new mongoose.Schema({
  userid: {type: String, unique: true},
  tokenid: {type: String, sparse: true, default: null},
  media: [{
    mediaid: String,
    mediaurl: String
  }]
})

Also, as @Saleem mentioned, in your model media is an object, not an array. So change change schema to:

var userschema = new mongoose.Schema({
  userid: {type: String, unique: true},
  tokenid: {type: String, sparse: true, default: null},
  media: [{
    mediaid: String,
    mediaurl: String
  }]
})