Mongoose と MongoDB を使用して、タスクをタスクのリストに保存しようとしています。タスク コレクションと対応するリスト ドキュメントに埋め込みドキュメントとして重複して保存したいと考えています。
正常に動作しますが、1 つだけ小さなことがあります。リストの埋め込みドキュメントには 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);
私のコントローラー/ルーター:
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)
});
それを達成するためにマングースを別の方法で使用できますか? または、リストに保存する前に、タスクを保存してからクエリを実行する必要がありますか?
アドバイスありがとうございます:-)