【发布时间】:2020-04-20 23:50:20
【问题描述】:
我想使用 mongoose 从多个文档中更新多个子文档。
我当前的代码是:
const ids: any[] = payload.imageIds.map(e => new ObjectId(e));
await this.userModel
.updateMany({ 'images._id': { $in: ids } }, { $inc: { 'images.$.views': 1 } })
.exec();
部分架构是:
export const UserSchema = new mongoose.Schema(
{
images: [ImageSchema],
}
const ImageSchema = new mongoose.Schema(
{
views: { type: Number, default: 0 },
},
但此代码仅更新 ids arr 中的最后一个元素。
【问题讨论】:
-
你能分享收藏吗?
-
您能否在问题中添加文档以及预期的输出?
-
请使用该代码 db.demo.updateMany({ 'images._id': { $in: ids } }, { $inc: { 'images.$[].views': 1 } })
-
Mahesh 使用 $[] 将更新来自该用户的所有图像。我只想更新 ids arr 中的图像