简体   繁体   中英

How we reference mongodb using populate method using node js

I have doing referencing using the populate method in node js , but I have no more idea about the populate method. In this code, i am a reference to user collection from my child collection. I have two collections one child and second user

This child collection

userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    index: true
}

This is user collection

    "firstname":{type:String},
    "lastname":{type:String}

I have send id from URL ( http://localhost:8000/v1/childPopulate/:57a4e4e67429b91000e225a5 ) and queried with my stored userId in child schema

This is node js

  this.childPopulate = function(req, res, next){
  var o_userid = req.params.id;
  var query = {userId:o_userid};

  Child.findOne(query).populate({
    path: 'userId',
    model: 'User',
    select: 'firstname lastname'
  }).exec(function(err,userinfo){
    if(err){
      return next(err);
    }else{
      res.send(userinfo);
      console.log(userinfo);
    }
  });
};

But this shows this error in browser

 {"message":"Cast to ObjectId failed for value \":57a4e4e67429b91000e225a5\" at path \"userId\""}

The error message indicates that you are passing a string instead of ObjectID. Basically the default id in mongodb is not a normal string. Its is a unique 12-byte identifier.

So you should convert the string to type ObjectID.

var query = {userId: mongoose.Types.ObjectId(stringId)};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM