简体   繁体   中英

Mongoose populate - Node.JS creating multiple objects

Task I have is to make a array of ie dishes that logged user is selecting as his favourite. Problem is that instead of one array of objectIDs ie dishes:[123456,5678910], i get two separate objects for same user with only one dish id in the array.

I presume that problem is in my schema, so can someone give me an idea?

var favoriteSchema = new Schema({

timestamps: true,


dishes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Dish'
}],

postedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
}

});

Edit>> My post method as 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 is fine for the first time you want to add a favorite dish. The next time you add a dish for the same user you 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);
    });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM