find id of latest subdocument inserted in mongoose

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

    If you have a separate schema for your subdocument, then you can create the new subdocument from a model before you push it on to your parent document and it will have an ID:

    var bSchema = new mongoose.Schema({
      ba: Integer,
      bb: String
    };
    
    var a = new mongoose.Schema({
      a: String,
      b : [ bSchema ]
    });
    
    var bModel = mongoose.model('b', bSchema);
    var subdoc = new bModel({
      ba: 5,
      bb: "hello"
    });
    
    console.log(subdoc._id);    // Voila!
    

    Later you can add it to your parent document:

    m['b'].push(subdoc)
    m.save(...
    

提交回复
热议问题