我有一个像这样的用户架构
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/