gpt4 book ai didi

node.js - Mongoose .js : _id of embedded document

转载 作者:可可西里 更新时间:2023-11-01 09:19:56 25 4
gpt4 key购买 nike

我正在尝试使用 mongoose 和 MongoDB 将任务保存到任务列表中。我想把它冗余地保存在任务集合和相应的列表文档中作为嵌入文档。

它工作正常,但有一点:列表的嵌入文档没有它们的 objectId。但我需要它们以便将它们与任务集合中的文档逻辑连接起来。

我的模式:

var TaskSchema = new Schema({
_id: ObjectId,
title: String,
list: ObjectId

});

var Task = mongoose.model('task', TaskSchema);

var ListSchema = new Schema({
_id: ObjectId,
title: String,
tasks: [Task.schema]
});

var List = mongoose.model('list', ListSchema);

我的 Controller /路由器:

app.post('/lists/:list_id/tasks', function(req, res) {

var listId = req.params.list_id;

// 1. Save the new task into the tasks-collection.

var newTask = new Task();
newTask.title = req.body.title;
newTask.list = listId;

console.log('TaskId:' + newTask._id); // Returns undefined on the console!!!

newTask.save(); // Works fine!

// 2. Add the new task to the coresponding list.

list.findById(listId, function(err, doc){

doc.tasks.push(newTask);

doc.save(); // Saves the new task in the list but WITHOUT its objectId

});

res.redirect('/lists/' + listId)

});

我可以使用 mongoose 以不同的方式实现吗?还是我必须保存任务,然后在将其保存到列表中之前查询它?

谢谢你的建议:-)

最佳答案

我使用一个名为 populate 的很棒的功能解决了这个问题!

此外,dtryon 是正确的:您不需要在模型中声明您的 _id ObjectId,无论如何它们都会被添加。而且你必须嵌套这些东西,因为你的任务是异步保存的,所以你必须确保它在其他东西之前运行。

解决方法如下:

模式:

var TaskSchema = new Schema({
title: String,
list: { type: Schema.ObjectId, ref: 'list' }

});

var Task = mongoose.model('task', TaskSchema);

var ListSchema = new Schema({
title: String,
tasks: [{ type: Schema.ObjectId, ref: 'task' }]
});

var List = mongoose.model('list', ListSchema);

Controller /路由器:

app.post('/lists/:list_id/tasks', function(req, res) {

var listId = req.params.list_id;

var newTask = new Task();
newTask.title = req.body.title;
newTask.list = listId;


// WHEN SAVING, WRAP THE REST OF THE CODE

newTask.save(function (err){
if (err) {
console.log('error saving new task');
console.log(err);
} else {
console.log('new task saved successfully');

list.findById(listId), function(err, doc){

doc.tasks.push(newTask);

doc.save(function (err){
if (err) {
console.log('error adding new task to list');
console.log(err);
} else {

console.log('new task saved successfully');
res.redirect('/lists/' + listId);

}
});
});
});
});
});

现在它可以正确引用并且使用填充功能您可以非常轻松地访问条目。像魅力一样工作:-)

关于node.js - Mongoose .js : _id of embedded document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10912530/

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