gpt4 book ai didi

node.js - 查找插入 mongoose 的最新子文档的 id

转载 作者:IT老高 更新时间:2023-10-28 13:07:22 24 4
gpt4 key购买 nike

我有一个模型架构:

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。

最佳答案

我也一直在寻找这个答案,但我不确定我是否喜欢访问数组的最后一个文档。但是,我确实有替代解决方案。 m['b'].push 方法将返回一个整数,1 或 0 - 我假设这是基于推送的成功(在验证方面)。但是,为了访问子文档,尤其是子文档的 _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 转换会立即发生(包括验证和类型转换之类的事情) - 这意味着这是创建 ObjectId 的时间;不是在模型保存回 Mongo 时。事实上,mongo 不会自动为子文档分配 _id 值,这是 mongoose 的特性。 Mongoose create 记录在这里:create docs

因此,您还应该注意,即使您有一个子文档 _id - 在您保存它之前它还不存在于 Mongo 中,因此请注意您可能采取的任何 DOCRef 操作。

关于node.js - 查找插入 mongoose 的最新子文档的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18760087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com