Mongoose:仅从嵌入文档的数组中返回 1 个文档并更新该返回的子文档的字段

问题描述

我是 mongomongoose 的新手。我正在尝试查询文档中的一些嵌入文档并仅更新第一个匹配子文档的字段。

我尝试过 $firstfindOnefindOneAndUpdate 和各种语法,但我对如何组合使用所有内容感到有些迷茫。在阅读文档和一些 SO 答案后,我现在正在使用 $aggreate,但我仍然得到一个列表,而不是 1 个单项。我得到的,因为这就是 $aggregate 的作用,它返回一个匹配项目的列表,但我只想得到第一个匹配的项目,我尝试使用 $limit,$first,和 $group$aggreate 但我现在很困惑。 ?

谢谢。

我有以下架构:


const stripeProductSchema = new mongoose.Schema({ 
    bundlePhotoCodes: [photoCodes]
})

module.exports = mongoose.model('StripeProduct',stripeProductSchema)
const photoCodeSchema = new mongoose.Schema({
  modelID: { type: String,unique: true,default: null},value: { type: String,trim: true,unique: true },validUntil: {type: Date,default: null },status: {
    type: String,enum: ['valid','expired','attributed'],default: 'valid',},{ strict: true,timestamps: true },)

module.exports = mongoose.model('PhotoCodes',photoCodeSchema)

这是我想要做查询

    StripeProduct.aggregate([
      { $match: { 'bundlePhotoCodes.status': 'valid'} },{ $unwind: '$bundlePhotoCodes' },{ $project: { bundlePhotoCodes: 1 } }
    ]).then((photoCode,err) => {
      console.log(photoCode)

      // here I will like to do something like  on that photoCode document
      // I think I should do this before I return from the $aggregate ?  
    const update = { 
      $set: {
        'bundlePhotoCodes.status': 'attributed','bundlePhotoCodes.modelID': modelID,'bundlePhotoCodes.validUntil': date.setMonth(date.getMonth() + ADD_THREE_MONTHS),} 
    })

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)