Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating in array of object ids

My schema:-

var playlistSchema = new Schema({
name        : {type:String,require:true},
videos      : {type:[mongoose.Schema.Types.ObjectId],ref: 'Video'},
},{collection:'playlist'})

var Playlist = mongoose.model('Playlist',playlistSchema);

I have some data in the database as exapmple:-

{
"_id" : ObjectId("58d373ce66fe2d0898e724fc"),
"name" : "playlist1",
"videos" : [ 
    ObjectId("58d2189762a1b8117401e3e2"), 
    ObjectId("58d217e491089a1164a2441f"), 
    ObjectId("58d2191062a1b8117401e3e4"), 
    ObjectId("58d217e491089a1164a24421")
],
"__v" : 0

}

And the schema of Video is :-

var videoSchema = new Schema({
name        : {type:String,required:true},
createdAt   : {type:String,default:new Date()},
isDisabled  : {type:Boolean,default:false},
album       : {type: mongoose.Schema.Types.ObjectId, ref: 'Album'}
},{collection:'video'})

var Video = mongoose.model('Video',videoSchema);

Now in order to get the name of the all the videos in playlist i am trying the code:-

 var playlistModel = mongoose.model('Playlist');
let searchParam = {};
searchParam._id = req.params.pid;
playlistModel.findOne(searchParam)
.populate('[videos]')
.exec(function(err,found){
    if(err)
        throw err;
    else{
        console.log(found.videos[0].name);
    }
})

But here i am getting the undefined result.I am not getting where i am wrong plzz anyone help me to short out this problem.

like image 504
lal rishav Avatar asked Mar 23 '17 12:03

lal rishav


People also ask

What does populate do in mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

What does it mean to populate an array?

In a primitive data type array, the elements are stored in a contiguous memory location. In contrast, in a non-primitive data type, the elements are stored in dynamic memory (Heap segment). In this tutorial, we populate an array in Java. Populate here means filling the array with some values.

What is mongoose ref?

The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.


1 Answers

got the answer:- just change the schema

var playlistSchema = new Schema({
name        : {type:String,require:true},
videos      : [{type:mongoose.Schema.Types.ObjectId,ref: 'Video'}],
},{collection:'playlist'})

var Playlist = mongoose.model('Playlist',playlistSchema);

and just use

.populate('videos')

instead of

.populate('[videos]')
like image 142
lal rishav Avatar answered Nov 13 '22 08:11

lal rishav