如何更新 MongoDB 中对象数组中的键?

How do I update a key in an array of objects in MongoDB?

我在 NodeJS 后端工作 API 并试图在我的 MongoDB 数据库中将对象数组中的键从 false 更改为 true。我从客户端传递了两个条件:用户的电子邮件和向用户发送消息的人的电子邮件。我想将 read 的布尔值更改为 true.

示例数据:

{
  _id: new ObjectId("6282163781acbcd969de3fc9"),
  firstName: 'Amanda',
  lastName: 'Nwadukwe',
  role: 'Volunteer',
  email: 'amandanwadukwe@gmail.com',
  password: 'a$YD5MQlMt0gqSULQOBNcEfOLr3vIK8eF4dqdLw3XctsIVgbnf54P32',
  confirmPassword: 'a$mnL0S1bDDkGVnKgqQP81mOew9aFdNTUCGOEs7LvWYRxzivN4hrtFS',
  date: 2022-05-16T09:14:57.000Z,
  messages: [
    {
      message: 'This is another message from Amanda',
      sendersEmail: 'laju@gmail.com',
      date: '2022-05-14T12:00:45.000Z',
      read: false
    },
    {
      sender: 'Amanda Nwadukwe',
      message: 'This is another message from Amanda',
      sendersEmail: 'amanda@gmail.com',
      date: '2022-05-14T12:00:45.000Z',
      read: false
    }]

期望的输出:

{
      _id: new ObjectId("6282163781acbcd969de3fc9"),
      firstName: 'Amanda',
      lastName: 'Nwadukwe',
      role: 'Volunteer',
      email: 'amandanwadukwe@gmail.com',
      password: 'a$YD5MQlMt0gqSULQOBNcEfOLr3vIK8eF4dqdLw3XctsIVgbnf54P32',
      confirmPassword: 'a$mnL0S1bDDkGVnKgqQP81mOew9aFdNTUCGOEs7LvWYRxzivN4hrtFS',
      date: 2022-05-16T09:14:57.000Z,
      messages: [
        {
          message: 'This is another message from Amanda',
          sendersEmail: 'laju@gmail.com',
          date: '2022-05-14T12:00:45.000Z',
          read: true
        },
        {
          sender: 'Amanda Nwadukwe',
          message: 'This is another message from Amanda',
          sendersEmail: 'amanda@gmail.com',
          date: '2022-05-14T12:00:45.000Z',
          read: false
        }]

我尝试了很多过滤方法,但都没有成功。这是我将所有 read 更改为 true 的代码。它也不起作用。

app.post("/view_message", (req, res) => {
  const email = req.body.email;
  
  Users.findOneAndUpdate({ "email": email }, {$set:{"messages.$.read": true}}, (err, result) => {
    console.log(result)
  })
});

您错过了添加检查以匹配要更新的数组元素。

Playground

db.collection.update({
  "email": "amandanwadukwe@gmail.com",
  "messages.sendersEmail": "laju@gmail.com", //This did the trick
  
},
{
  "$set": {
    "messages.$.read": true
  }
},
{
  "multi": false,
  "upsert": false
})

以防万一有人需要它,更新数组中所有对象的所有读取值我使用了这个:

User.findAndUpdateOne({
  "email": "amandanwadukwe@gmail.com",
  "messages.sendersEmail": "laju@gmail.com", 
  
},
{
  "$set": {
    "messages.$[].read": true //Added square brackets
  }
},
{
  "multi": false,
  "upsert": false
})