Useful mongoose functions - nsyncCSUS/seniorproject GitHub Wiki

How to add to a mongoose model.

$(denotes mongodb function)
$push - adds to array $addToSet - same as $push but wont add duplicates
$pull - deletes from array

Example

  groups.put('/:gid', function(request, response, next) {
    var uid = request.params.uid;
    var groupToAdd = request.params.gid;
    User.findByIdAndUpdate(uid,{$addToSet: {"subscribedTo":groupToAdd}}, function(err, user) {
      if (err) {
        return util.err(err, response);
      }else{
        response.send(user);
      }
    });
  });

Performing a table join for nested data

In the event that you have some nested collection of data, you can use the populate() method that exists for mongoose result sets to pull that nested data into the current collection. Note however that populate only imports objects that are declared as the 'ObjectId' type and have a proper reference to an existing table.

Example:

exports.index = function(req, res) {
    Group.findById(req.params.id)
        .populate('events') // Populate group data with nested event list
        .exec(function(err, group) {
            res.json({group: group});
        });
};