find id of latest subdocument inserted in mongoose

前端 未结 4 1613
自闭症患者
自闭症患者 2020-12-15 21:21

i have a model schema as :

var A = new Schema ({
  a: String,
  b : [ { ba: Integer, bb: String } ]
}, { collection: \'a\' } );

then

<
4条回答
  •  执笔经年
    2020-12-15 21:43

    The question is "a bit" old, but what I do in this kind of situation is generate the subdocument's id before inserting it.

    var subDocument = {
        _id: mongoose.Types.ObjectId(),
        ba:235,
        bb:"World"
    };
    
    m['b'].push(subDocument);
    
    m.save(function(err,model){
      // I already know the id!
      console.log(subDocument._id);
    });
    

    This way, even if there are other database operations between the save and the callback, it won't affect the id already created.

提交回复
热议问题