Cast plain object to mongoose document

后端 未结 2 1615
广开言路
广开言路 2021-01-17 07:43

UPDATE 1: 5 votes have been received, so I have submitted a feature request: https://github.com/LearnBoost/mongoose/issues/2637

Please cast your +1

2条回答
  •  无人共我
    2021-01-17 08:03

    1. If you are getting a response from REST service and say you have a User mongoose model

    var User = mongoose.model('User');
    var fields = res.body; //Response JSON
    var newUser = new User(fields);
    newUser.save(function(err,resource){
      console.log(resource);
    });

    1. In other case say you have an array of user JSON objects from User.find() that you want to query or populate

    var query  = User.find({});
    query.exec(function(users){
      //mongoose deep-populate ref docs
      User.deeppopulate users 'email_id phone_number'.exec({
        //query through populated users objects
      });
    });

    MongoDB doesn't support Joins and Transfers. So for now you can't cast values to an object directly. Although you can work around it with forEach.

提交回复
热议问题