find插入mongoose的最新子文件的id

我有一个模型架构为:

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

然后

  var M = mongoose.model("a", A); var saveid = null; var m = new M({a:"Hello"}); m.save(function(err,model){ saveid = model.id; }); // say m get the id as "1" 

然后

  m['b'].push({ba:235,bb:"World"}); m.save(function(err,model){ console.log(model.id); //this will print 1, that is the id of the main Document only. //here i want to find the id of the subdocument i have just created by push }); 

所以我的问题是如何find刚刚推入模型的一个字段中的子文档的id。

我也一直在寻找这个答案,我不确定我喜欢访问数组的最后一个文档。 不过,我确实有一个替代解决scheme。 方法m['b'].push将返回一个整数,1或0 – 我假设是基于推的成功(就validation而言)。 但是,为了访问子文档,尤其是子文档的_id,应该先使用create方法,然后push

代码如下:

 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); }); 

发生的事情是,当你将对象传递给push或create方法时,Schema强制转换(包括validation和types转换等) – 这意味着这是ObjectId被创build的时间; 而不是当模型保存到Mongo。 实际上,mongo不会自动将_id赋值给子文档,这是一个mongoose特征。 Mongoose创buildlogging在这里: 创build文档

因此,你也应该注意到,即使你有一个子文档_id – 在你保存它之前它还没有在Mongo中,所以你可能会厌倦任何的DOCRef操作。

Mongoose会自动为每个新的子文档创build一个_id,但据我所知,在你保存时不会返回这个。

所以你需要手动获取它。 save方法将返回保存的文档,包括子目录。 当你使用push你会知道这将是数组中的最后一项,所以你可以从那里访问它。

像这样的事情应该做的伎俩。

 m['b'].push({ba:235,bb:"World"}); m.save(function(err,model){ // model.b is the array of sub documents console.log(model.b[model.b.length-1].id); }); 

问题是“有点老”,但是我在这种情况下做的是在插入子文档之前生成子文档的ID。

 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); }); 

这样,即使在保存和callback之间还有其他数据库操作,也不会影响已经创build的ID。

如果您有一个单独的模式为您的子文档,然后您可以从模型中创build新的子文档,然后将它推送到您的父文档,它将有一个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! 

稍后,您可以将其添加到您的父文档中:

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