猫鼬用来自其他字段的值更新值

时间:2021-06-28 13:19:48

标签: mongodb mongoose

我可以使用此文档中的其他值更新 findOneAndUpdate 中的值吗?

我的数据结构看起来像

User: {
  email: "test@mail.com",
  test: {
    token: "someFancyToken",
    email: "other-email@test.com"
  }
}

我希望如何更改数据

await UserModel.findOneAndUpdate(
  {
    'test.token': token,
  },
  {
    email: test.email,
    test: null
  },
)

输出

User: {
  email: "other-email@test.com",
  test: null
}

1 个答案:

答案 0 :(得分:1)

从 MongoDB 4.2 开始,您可以使用聚合管道进行更新操作,因此您可以执行以下操作:

await UserModel.findOneAndUpdate(
  { 'test.token': token },
  [{ $set: { email: "$test.email", test: null } }]
)