我有一个模型用户,其中包含徽章列表
badges: [{type:mongoose.Schema.Types.ObjectId, ref: 'badge'}]
在创建新徽章时,我想将此徽章添加到特定用户的徽章列表中
User.findById(id, function(err,user){
user.badges.push(???) ///// How to push the badge I'm creating
user.save(..)
})
如何做到这一点?
最佳答案
在推送到 user.badges 之前,您必须保存徽章。 Mongodb 自动设置徽章._id 属性。
var badge = new Badge(...);
badge.save().then(badge=>{
user.badges.push(badge._id);
user.save;
});
关于javascript - 如何在创建另一个文档的同时在一个文档中创建字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44113538/