node.js - Mongoose 通过 id 更新数组中的项目

标签 node.js mongodb mongoose

在一个使用 mongoose 的 Node js 项目中,我试图更新文档内的数组项。
我有一个 users 架构,其中有一个 notifications 数组。每个用户都有一个 _id,每个通知项目都有一个 _id

如何通过用户 ID 和通知 ID 更新通知?

用户架构:

const schema = mongoose.Schema({
  notifications: [{
    id: { type: mongoose.Schema.ObjectId },
    title: { type: String },
    body: { type: String },
    isRead: { type: Boolean, default: false },
    date: { type: Date }
  }],
  token: { type: String },
  isActive: { type: Boolean, default: false }
}, { timestamps: {} }) 

这是我迄今为止尝试过的:

exports.updateNotification = (req, res) => {

  // Note: in req.params I receive id(for user id) and notificationId.

  UserModel.findByIdAndUpdate(req.params.id, { $set: { notifications: req.body } }, { safe: true, upsert: true, new: true })
    .then((result) => res.status(201).json({
      success: true,
      message: res.__('success.add'),
      user: result
    }))
    .catch(err => errorHandler.handle(err, res))
}

方法findByIdAndUpdate我用它来更新用户,但我不知道如何调整它以通过id更新通知。

最佳答案

尝试使用$elemMatch

UserModel.findOneAndUpdate({_id: 1, notifications: {$elemMatch: {id: 2}}},
                           {$set: {'notifications.$.title': req.body.title,
                                   'notifications.$.body': req.body.body,}}, // list fields you like to change
                           {'new': true, 'safe': true, 'upsert': true});

关于node.js - Mongoose 通过 id 更新数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741974/

相关文章:

node.js - 使用 ts-node 时通过 fork() 调用子进程

java - 如何使用Java驱动程序在MongoDB中按用户名获取每个用户组的最后一个文档?

node.js - 任何使用 mongo db 完成用户集成的 node.js 示例?

node.js - 我有 2 个相同的 ID,但当我尝试查找它们是否相等时,结果却不同

javascript - 通过 mongoose 更新 mongodb 内嵌套数组中的特定值

javascript - 使用 Express 获取表单数据到 mongoDB 数据库

node.js - block 不适用于 nodejs 和 Jade

node.js - MongoDB 获取两个数字字段之间的文档

javascript - Mongoose 聚合不排序日期

node.js - Node.js 中的准确计时