【问题标题】:How do I remove a specific item from model's array?如何从模型的数组中删除特定项目?
【发布时间】:2018-11-29 06:52:10
【问题描述】:

这是我的带有watchedwatchLater 数组的用户模型:

const UserSchema = new mongoose.Schema(
  {
    email: { type: String, required: true, unique: true },
    watched: [{ type: Number }],
    watchLater: [{ type: Number }],
  },
  { timestamps: true },
)

我有这个功能,我想从watchLater 中删除 id 并添加到watched

  async addToWatched(id) {
    const _id = this.getUserId()
    return await this.store.User.findByIdAndUpdate(
      { _id },
      // remove id from watchLater and add to watched,
      { new: true },
    )
  }

我该怎么做?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    阅读了一些文档。这似乎有效:

    return await this.store.User.findByIdAndUpdate(
      { _id },
      // remove id from watchLater and add to watched,
      { $pull: { watchLater: id }, $addToSet: { watched: id } },
      { new: true },
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-21
      • 2016-12-19
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多