How to push to an array in mongoose How to push to an array in mongoose mongoose mongoose

How to push to an array in mongoose


Query the User user using findOne() first and use the first found document that's passed to the callback to save the embedded documents with:

router.post('/setsuggestions', function(req, res, next){    if(!req.body.username || !req.body.challengessuggestions){        return res.status(400).json({message: challengessuggestions});    }    var query = { username: req.body.username };    User.findOne(query, function (err, user){               if (err) //throw ...        if (user) {            if (user.challengessuggestions && user.challengessuggestions.length) {                user.challengessuggestions.push(req.body.challengessuggestions);            }            else {                user.challengessuggestions = [req.body.challengessuggestions];            }            // save changes            user.save(function (err) {                if (!err) {                    // done ...                }            });        }    });    );