查找在猫鼬中插入的最新子文档的ID [英] find id of latest subdocument inserted in mongoose

查看:47
本文介绍了查找在猫鼬中插入的最新子文档的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
    });

所以我的问题是如何找到刚在模型的一个字段中推送的子文档的ID.

So my question is how to find the id of the subdocument just pushed in one field of the model.

推荐答案

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

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.

代码如下:

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强制转换(包括诸如验证和类型强制转换之类的东西)-这意味着这是创建ObjectId的时间;将模型保存回Mongo时不可以.实际上,mongo不会自动将_id值分配给子文档,这是mongoose的功能.猫鼬创建记录在这里:创建文档

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

因此,您还应该注意,即使您有一个子文档_id-在保存它之前,它都不会在Mongo中使用,所以请对可能执行的任何DOCRef操作感到厌倦.

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.

这篇关于查找在猫鼬中插入的最新子文档的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆