MongoDB与 Mongoose :如何将对象推送到嵌套的文档数组中?

pvcm50d1  于 2023-01-17  发布在  Go
关注(0)|答案(1)|浏览(140)

我有我的MongoDB,遵循这个模式:

const userSchema = new Schema(
  {
   (...),
    therapy_records: {
     (...),
      daily_record: [
        {
          therapy_day: '',
          date: '',
          consumed: '',
          limit: '',
          goal: '',
          morning_timer: '',
        },
      ],          
  },    
)

我尝试addAsNewItemIfArrayExists/createIfNotExists每次都推送一个新的daily_record对象,但我下面的代码只是添加一个只有“_id”的对象,如果daily_record不存在,则没有记录。当它存在时,它什么也不做。
有没有人知道哪种方法是正确的?Thx!

const user = await User.findByIdAndUpdate(
  userId,
  {
    therapy_records: {
     (..),
     daily_record: {
          $push: [
            {
              therapy_day: anyNumber,
              date: anyDate,
              consumed: anyNumber,
              limit: anyNumber,
              goal: anyNumber,
              morning_timer: anyNumber,
            },
          ],
        },
      
     (...),
    },
  },
  { new: true, upsert: true }
)
cuxqih21

cuxqih211#

您需要用途:

const user = await User.findByIdAndUpdate(
  userId,
  {
      $push: {
        'therapy_records.daily_record': {
          therapy_day: *anyNumber*,
          date: *anyNumber*,
          consumed: *anyNumber*,
          limit: *anyNumber*,
          goal: *anyNumber*,
          morning_timer: *anyNumber*,
        },
      },
  },
  { new: true, upsert: true }
)

相关问题