javascript - Mongoose populate - Node.JS creating multiple objects -
task have make array of i.e. dishes logged user selecting favourite. problem instead of 1 array of objectids i.e. dishes:[123456,5678910], 2 separate objects same user 1 dish id in array.
i presume problem in schema, can give me idea?
var favoriteschema = new schema({ timestamps: true, dishes: [{ type: mongoose.schema.types.objectid, ref: 'dish' }], postedby: { type: mongoose.schema.types.objectid, ref: 'user' } });
edit>> post method demanded
.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); }); });
your post method fine first time want add favorite dish. next time add dish same user should call
favorites.findone({postedby: req.decoded._doc._id}, function (err, favorite) { favorite.dishes.push(req.body); favorite.save(function (err, favorite) { if (err) throw err; res.json(favorite); }); })
Comments
Post a Comment