首页 > 解决方案 > 由于某种原因,用户没有更新

问题描述

我想向用户添加一个包含其创建文件路径的字段,它是一个数组pathArray,但由于某种原因它没有更新await userService.updateUser({ _id }, { photos: pathArray });
服务本身updateUser: (user, updatedUser) => User.updateOne(user, updatedUser)
服务返回这样一个对象{ n: 0, nModified: 0, ok: 1 }
用户模型:

  photos: {
    type: Array
  }

{ photos: pathArray }- 一个看起来像这样的数组:

{
  photos: [
    {
      pathForDB: 'users\\60e6c6e56d2df72d1881c57a\\photos\\8bd722f0-e22d-11eb-b487-df8a875defa8.jpg',
      timestamp: '11.07.2021, 12:51:21'
    },
    {
      pathForDB: 'users\\60e6c6e56d2df72d1881c57a\\photos\\8be18330-e22d-11eb-b487-df8a875defa8.jpg',
      timestamp: '11.07.2021, 12:51:21'
    }
  ]
}

标签: node.jsmongoose

解决方案


最好使用 User.findOne() 找到用户,然后更新并保存回来。使用此方法,您始终可以检索更新的数据。

const user =User.findOne({
  _id: userId
});
user.files= pathArray //method to update
const result = await user.save()
res.status(200).json({
  user: result
});

推荐阅读