【问题标题】:update in pre save hook在预保存挂钩中更新
【发布时间】:2018-06-10 13:49:14
【问题描述】:

我有这样的用户架构

const userSchema = new Schema({
  username: {
    type: String,
    unique: true,
    required: true,
  }, 
  cardIds: [{
    type: Schema.Types.ObjectId,
    ref: 'cards',
  }],
})
mongoose.model('users', userSchema)

我试图在用户的预保存挂钩中做两件事:首先,使用用户 ID 保存每张卡,其次,将 cardIds 添加到用户。我的代码:

const Card = mongoose.model('cards')

userSchema.pre('save', function (next) {
  if (this.cardIds.length === 0) {
    cardList.forEach(async card => {
      const newCard = await new Card({ ...card, user: this })
      this.cardIds.push(newCard) // this is not working
      newCard.save() // this is working
    })
  }
  next()
})

这会将带有正确user._id 的每张卡片添加到cards 集合中,但是,每个用户仍将有一个cardIds 的空数组。

我保存用户的方式是(为了方便省略了错误处理/验证):

app.post('/users/new', async (req, res) => {
  const newUser = await new User({ username: req.body.username })
  await newUser.save()
  return res.json({ message: 'User created successfully' })
})

【问题讨论】:

  • 请发布创建用户查询
  • 其实userSchema还有另外一个属性username,所以在post路由我就做const newUser = await new User({ username: req.body.username }); newUser.save();
  • 请更新您的问题而不是评论
  • 我刚刚更新了,谢谢:)

标签: node.js mongodb express mongoose


【解决方案1】:

这基本上是一个 javascript 代码 this.cardIds.push(newCard) 将元素推送到数组,但它对您的 mongo 数据库没有任何作用......

因此,要更新 mongodb 中的数组,您需要使用 $push 运算符

userSchema.pre('save', function (next) {
  if (this.cardIds.length === 0) {
    cardList.forEach(async card => {
      const newCard = new Card({ ...card, user: this })
      const saveNewCard = await newCard.save() // this is working
      const updateUser = await User.update(
        { _id: this._id },
        { $push: { cardIds: saveNewCard._id }}
      )
    })
  }
  next()
})

【讨论】:

  • 嗨,@Ashnish。你在哪里从User.update 中获取User?谢谢
猜你喜欢
  • 2020-05-13
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 2020-11-18
  • 1970-01-01
  • 2017-08-19
相关资源
最近更新 更多