【问题标题】:How to update a mongo nested array in nodejs?如何更新nodejs中的mongo嵌套数组?
【发布时间】:2022-01-24 05:30:22
【问题描述】:

这是我的模型:

const userSchema = mongoose.Schema({
    given_name: { type: String, required: true },
    email: { type: String, required: true },
    picture: { type: String },
    id: { type: String },
    shelf: [{ readlist: [String] }]
})

在用户的书架内,还有一个名为 readlist 的数组。每次用户将一本书添加到他的阅读列表时,这都会更新。 我在创建用户时尝试了以下方式:

User.create({ email: email, given_name: given_name, picture: picture, id: sub, shelf: {readlist: []} });

但它正在架子数组内创建一个对象。 如何直接在shelf数组里面创建一个readlist数组,并在readlist里面添加值?

【问题讨论】:

  • 你的架子是故意的吗?
  • 是的,我希望里面有阅读清单、待阅读清单和阅读清单。
  • 所以,我认为将它们组织起来是个好主意。

标签: node.js mongodb web mongoose mern


【解决方案1】:

您可以尝试使用定位operator $:

User.updateOne({
  _id
},
{
  "$push": {
    "shelf.$.readlist": book
  }
})

【讨论】:

  • 创建用户时如何创建货架?
  • 该代码仅在我删除 $ 时才有效。
猜你喜欢
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 2017-01-05
  • 2017-01-05
  • 1970-01-01
  • 2021-07-20
  • 2023-03-07
相关资源
最近更新 更多