【发布时间】:2016-09-03 23:31:32
【问题描述】:
我的任务是制作一系列即登录用户选择为他最喜欢的菜肴。问题是,我得到的不是一个 objectID 数组,即菜:[123456,5678910],而是同一用户的两个单独的对象,数组中只有一个菜 id。
我认为问题出在我的架构中,那么有人可以给我一个想法吗?
var favoriteSchema = new Schema({
timestamps: true,
dishes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Dish'
}],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
编辑>>按要求发帖方法
.post(Verify.verifyOrdinaryUser, function (req, res, next) {
Favorites.create(req.body, function (err, favorite) {
if (err) throw err;
console.log('favorite created!');
var id = favorite._id;
favorite.postedBy = req.decoded._doc._id;
favorite.dishes.push(req.body);
favorite.save(function (err, favorite) {
if (err) throw err;
console.log('Updated Favorites!');
res.json(favorite);
});
});
【问题讨论】:
-
你能发布你是如何创建条目的吗?您的架构似乎没问题。
-
我已经编辑了帖子,并提交了我的 .post 方法。这种创建方法可能是我的问题,但我不确定该使用什么...... @Apokalyptra
-
如何让菜的
id推送到dishes数组? -
@chridam
favorite.dishes.push(req.body); -
所以
req.body是这道菜的id,而不仅仅是一个对象?我要问的原因是dishes字段是ids 的菜数组,而不是对象。
标签: javascript node.js mongodb mongoose-populate