find id of latest subdocument inserted in mongoose

前端 未结 4 1648
自闭症患者
自闭症患者 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:52

    I've been looking for this answer as well, and I'm not sure that I like accessing the last document of the array. I do have an alternative solution, however. The method m['b'].push will return an integer, 1 or 0 - I'm assuming that is based off the success of the push (in terms of validation). However, in order to get access to the subdocument, and particularly the _id of the subdocument - you should use the create method first, then push.

    The code is as follows:

    var subdoc = m['b'].create({ ba: 234, bb: "World" });
    m['b'].push(subdoc);
    console.log(subdoc._id);
    m.save(function(err, model) { console.log(arguments); });
    

    What is happening is that when you pass in the object to either the push or the create method, the Schema cast occurs immediately (including things like validation and type casting) - this means that this is the time that the ObjectId is created; not when the model is saved back to Mongo. In fact, mongo does not automatically assign _id values to subdocuments this is a mongoose feature. Mongoose create is documented here: create docs

    You should also note therefore, that even though you have a subdocument _id - it is not yet in Mongo until you save it, so be weary of any DOCRef action that you might take.

提交回复
热议问题