Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongoose“为”在post中间件上填充;“保存”; 请考虑下面的 PARTESTMAS/和子模式< /代码>: const parentSchema = new mongoose.Schema({ name: String, children: [{ type: mongoose.Schema.Types.ObjectId, ref: "Child" }], }); const childSchema = new mongoose.Schema({ name: String, parent: { type: mongoose.Schema.Types.ObjectId, ref: "Parent" }, });_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js Mongoose“为”在post中间件上填充;“保存”; 请考虑下面的 PARTESTMAS/和子模式< /代码>: const parentSchema = new mongoose.Schema({ name: String, children: [{ type: mongoose.Schema.Types.ObjectId, ref: "Child" }], }); const childSchema = new mongoose.Schema({ name: String, parent: { type: mongoose.Schema.Types.ObjectId, ref: "Parent" }, });

Node.js Mongoose“为”在post中间件上填充;“保存”; 请考虑下面的 PARTESTMAS/和子模式< /代码>: const parentSchema = new mongoose.Schema({ name: String, children: [{ type: mongoose.Schema.Types.ObjectId, ref: "Child" }], }); const childSchema = new mongoose.Schema({ name: String, parent: { type: mongoose.Schema.Types.ObjectId, ref: "Parent" }, });,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,如何在childSchema的post中间件中访问父级的名称? 我正在尝试下面的代码,但是parent被分配了ObjectId,而不是实际的父模型 childSchema.post("save", async function (child) { const parent = child.populate("parent").parent; }); 正确的方法是什么?如果要在初始提取后填充内容,需要调用execPopulate——例如: chil

如何在childSchema的post中间件中访问父级的名称? 我正在尝试下面的代码,但是
parent
被分配了ObjectId,而不是实际的父模型

childSchema.post("save", async function (child) {
    const parent = child.populate("parent").parent;
});

正确的方法是什么?

如果要在初始提取后填充内容,需要调用
execPopulate
——例如:

childSchema.post(“保存”),异步函数(子函数){
试一试{
如果(!child.populated('parent')){
等待child.populate('parent').execPopulate();
}
const parent=child.populate(“parent”).parent;
}捕获(错误){}
});

我刚刚发现了
这个.model(“model”)
所以我正在分享另一个解决方案。不确定它与公认的相比如何,不过:

childSchema.post("save", async function (child) {
    try {
        const parent = await this.model("Parent").findOne({ _id: child.parent });
        parent.children.push(child._id);
        parent.save();
    } catch (error) {}

});

在填充之前使用wait,我知道在填充结束时的
.parent
是什么query@MohammadYaserAhmadi这没什么区别。顺便说一句,
child
是一个模型,而不是一个查询。要获取插入到其他集合(父集合)中的附加信息,需要查询