Cast plain object to mongoose document

后端 未结 2 1614
广开言路
广开言路 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.

    0 讨论(0)
  • 2021-01-17 08:16

    Posting my own answer so this doesn't stay open:

    Version 4 models (stable released on 2015-03-25) now exposes a hydrate() method. None of the fields will be marked as dirty initially, meaning a call to save() will do nothing until a field is mutated.

    https://github.com/LearnBoost/mongoose/blob/41ea6010c4a84716aec7a5798c7c35ef21aa294f/lib/model.js#L1639-1657

    It is very important to note that this is intended to be used to convert a plain JS object loaded from the database into a mongoose document. If you are receiving a document from a REST service or something like that, you should use findById() and update().

    For those who live dangerously:

    If you really want to update an existing document without touching the database, I suppose you could call hydrate(), mark fields as dirty, and then call save(). This is not too different than the method of setting doc.isNew = false; as I suggested in my original question. However, Valeri (from the mongoose team) suggested not doing this. It could cause validation errors and other edge case issues and generally isn't good practice. findById is really fast and will not be your bottleneck.

    0 讨论(0)
提交回复
热议问题