[英]Update element in array in Mongoose
例如,我想更新数组中任务的第一个 object。 请记住,tasks 数组属于另一个数组。
例如。 {“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
您可以像这样使用更新来更新任务:
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)
})
我是个白痴。 我通过在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 } }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.