简体   繁体   English

使用Mongoose更新数组中的项目?

[英]Update item in array with Mongoose?

I'm trying to update a single "todo" item in an array of todos stored in a specific user's todos array. 我正在尝试更新存储在特定用户的todos数组中的todos数组中的单个“todo”项。 A typical user may look something like this: 典型用户可能看起来像这样:

{ isAdmin: false,
  _id: 5cefe9b72efc1c19a0318233,
  username: 'a',
  email: 'aaaaa@gmail.com',
  todos:
    [ { day: 'Monday',
        completed: false,
        _id: 5cf10e7fba969c4be4d356db,
        name: 'asdf',
        createdDate: 2019-05-31T11:22:39.423Z,
        __v: 0 },
      { day: 'Monday',
        completed: false,
        _id: 5cf10e8bba969c4be4d356dc,
        name: 'pp',
        createdDate: 2019-05-31T11:22:51.248Z,
        __v: 0 }],
  __v: 12 }

When a user creates a todo, the todo is created with another Todo model and pushed into the user's todos array. 当用户创建待办事项时,todo将使用另一个Todo模型创建并推送到用户的todos数组中。 At first, I tried simply finding and updating the single todo with: 起初,我尝试使用以下方法简单地查找和更新单个待办事项:

db.Todo.findOneAndUpdate({_id: req.params.todoId}, req.body, {new: true})
   .then(function(updatedTodo) {
       res.json(updatedTodo);
   })
   .catch(function(err) {
       res.send(err);
   })

...and it seems to update the todo within the Todos collection, but it doesn't update the todo that's nested in the user's "todos" array. ...它似乎更新了Todos集合中的待办事项,但它没有更新嵌套在用户的“todos”数组中的待办事项。 So, I thought I'd resort to first finding the user and updating the id of the specific todo like so: 所以,我认为我会首先找到用户并更新特定待办事项的ID,如下所示:

User.findById(req.user._id, function(err, user) {
    if (err) {
        console.log(err);
    } else {
        user.todos.forEach(function(todo) {
            if (todo._id == req.params.todoId) {
                todo.completed = !todo.completed;
            }
    }
});

...but again, it doesn't seem to actually update the todo nested in the User's "todos" array. ...但是,它似乎并没有实际更新嵌套在用户的“todos”数组中的待办事项。 I'm a bit lost here and not sure where to go. 我有点迷失在这里,不知道该去哪里。 Any help would be extremely appreciated. 任何帮助将非常感激。

In case of User.findById() , is not enough to change todo.completed value. 如果是User.findById() ,则不足以更改todo.completed值。 You have to save it as well. 你也必须保存它。 For example: 例如:

User.findById(req.user._id)
.then(user => {
    user.todos.forEach(function(todo) {
        if (todo._id === req.params.todoId) {
            todo.completed = !todo.completed;
        }
    })
    return user.save();
})
.then(result => {
   res.json(result);
})
.catch(function(err) {
    res.send(err);
})

You can use async/await for this. 您可以使用async / await。

user = await User.findById(req.user._id);
user.todos[user.todos.findIndex(i=>i._id==="todos id")].complated = true;
user.save();

or 要么

User.findById(req.user._id, function(err, user) {
   if (err) {
      console.log(err);
   } else {
      user.todos.forEach(function(todo,index) {
         if (todo._id === req.params.todoId) {
            user.todos[index].completed = true;
         }
      User.updateOne({_id:req.user._id},user).exec();
}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM