node.js - 在预保存 Hook 中更新

标签 node.js mongodb express mongoose

我有一个像这样的用户架构

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

我尝试在用户的预保存 Hook 中执行两件事:首先,使用用户 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()
})

这会将每张卡添加到cards中正确的集合user._id但是,每个用户仍然有一个空数组 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' })
})

最佳答案

这基本上是一个 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()
})

关于node.js - 在预保存 Hook 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50784364/

相关文章:

javascript - 离开命令 Discord JS

mongodb - mongodump 给出段错误

node.js - 如何在模式数组中发布和更新模式并打印它?

javascript - Node.js API 与 express 和 mysql - WHERE IN 和带有多个逗号分隔值的绑定(bind)参数

javascript - Express.js 代理发布请求

node.js - MongooseJS - 如何推送正确的格式?

json - 从 json 对象中提取子对象

node.js - mongodb db.open() 返回副本集错误但 mongodb 日志文件中没有错误

mongodb - 检查字段是否存在于数组的子文档中

node.js - 如何使用 mongodb、node.js、express 和 EJS 创建动态站点地图?