例如,我想更新数组中任务的第一个对象。请记住,任务数组属于另一个数组。
例如{“ firstName”:“多行”, “ lastName”:“多行”}
我尝试了以下操作,但是无法正常工作:
const index = req.params.id;
const { firstName, lastName, taskIndex } = req.body;
const foundTask = await Task.findById(index); //to Find index from parent array
const foundTaskItem = await foundTask.tasks[taskIndex]; // to find the object to update
// Need correct below
Task.update(
{ _id: ObjectId(index), tasks: foundTaskItem },
{ $push: { }
); // I feel this is wrong
[
{
"tasks": [
{
"firstName": "multiple lines",
"lastName": "multiple lines"
},
{
"firstName": "multiple lines2",
"lastName": "multiple lines2"
}
],
"_id": "5f22e48a97097d24e416bdf9",
"additional": "testing",
"date": "2020-07-30T15:17:30.236Z",
"__v": 0
},
{
"tasks": [
{
"firstName": "Michael ",
"lastName": "Jordan"
},
{
"firstName": "Scottie",
"lastName": "Pippen"
}
],
"_id": "5f248750e2e0b01180c49283",
"additional": "Chicago Bulls",
"date": "2020-07-31T21:04:16.519Z",
"__v": 0
}
]
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/ChDcJ.png
答案 0 :(得分:0)
您可以使用以下更新来更新任务:
Task.findOneAndUpdate(
{ _id: ObjectId(index), tasks.firstName: "multiple lines2" },
{ $set: { "tasks.$.firstName": "updated multiple lines2" } },
{ new: true, sort: { _id: -1 } }).exec()
.then(result => {})
.catch(error => {
console.log(error)
})
答案 1 :(得分:0)
我是个白痴。我通过在行const foundTaskItem = await foundTask.tasks[taskIndex].firstName
中添加.firstName来解决它;并使用foundTaskItem作为“ tasks.firstName”的值:。
const index = req.params.id;
const { firstName, lastName, taskIndex, additional } = req.body;
console.log(taskIndex);
const foundTask = await Task.findById(index);
const foundTaskItem = await foundTask.tasks[taskIndex].firstName;
Task.findOneAndUpdate(
{ _id: index, "tasks.firstName": foundTaskItem },
{ $set: { "tasks.$.firstName": firstName } },
{ new: true, sort: { _id: -1 } }
)