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

示例数据:

{
  _id: new ObjectId("6282163781acbcd969de3fc9"),
  firstName: 'Amanda',
  lastName: 'Nwadukwe',
  role: 'Volunteer',
  email: 'amandanwadukwe@gmail.com',
  password: '$2a$10$YD5MQlMt0gqSULQOBNcEfOLr3vIK8eF4dqdLw3XctsIVgbnf54P32',
  confirmPassword: '$2a$10$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: '$2a$10$YD5MQlMt0gqSULQOBNcEfOLr3vIK8eF4dqdLw3XctsIVgbnf54P32',
      confirmPassword: '$2a$10$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
        }]

我try 了很多过滤的方法,但都没有成功.这是我将所有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
})

Node.js相关问答推荐

根据我的测试,为什么在编写Varint代码方面,NodeJS要比Rust快这么多?

为什么在导出的函数中调用node-sqlite3中的数据库方法时不起作用?

获取驱动器文件夹的直接子文件夹时出现问题

Rails 7导入npm yaml包时出现404错误

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

为什么它无法发送发布请求并更改为 chrome 中的获取方法?

express 和 mongoose 的新密码不正确

如何在mongodb中获取对象数组内部的数据

在 nodejs 中使用 multer 上传文件返回未定义的 req.file 和空的 req.body

如何找到特定文档并更新数组中特定键的值?

使用 create-expo-app 时如何更改 webpack-config.js 中的哈希函数?

为什么我的react 表单不能正常工作?

如何在 mongoDB 中用值 0 填充缺失的文档?

使用服务帐户将 Firebase 应用程序部署到 Heroku(使用 dotenv 的环境变量)

分块 WebSocket 传输

使用 Node.JS,如何按时间顺序获取文件列表?

容器之间的 Docker HTTP 请求

将变量传递给nodemailer中的html模板

如何在 MongoDB 上只收听 localhost

如何从 Node.js 中的 URL 获取