【发布时间】: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