node package manager
Don’t reinvent the wheel. Reuse code within your team. Create a free org »

mongoose-helpers

Mongoose Helpers

Provides some helpers methods for Mongoose. Generally it makes it easier to search/manipulate embedded documents.

Install

npm install mongoose-helpers

Examples

Given the following models

var SongSchema = new Schema({
    name: String
});
 
var AlbumSchema = new Schema({
    songs: [SongSchema],
    name: String,
    releaseDate: Date,
    trackNum: Number
});
 
var ArtistSchema = new Schema({
    albums: [AlbumSchema],
    name: String
});
 
this.Artist = mongoose.model('Artist', ArtistSchema);

...you can now do the following:

Artist.findOne({ name: 'Nine Inch Nails' }, function(error, artist) {
    
    // Sort the albums by release date, ascending 
    artist.albums.sortAsc('releaseDate');
    
    // Sort the albums by release date, descending 
    artist.albums.sortDesc('releaseDate');
    
    // You can even sort by functions. This example sorts albums by least amount of songs to greatest 
    artist.albums.sortAsc('songs.length');
    
    // Filter embedded documents by different properties. Unlike mongoose, this 
    // function returns the found objects in an array instead of relying on a 
    // callback 
    artist.albums.find({ name: 'Pretty Hate Machine' });
    
    // ...and the findOne function only returns one object 
    artist.albums.findOne({ name: 'Pretty Hate Machine' });
    
    // It works with all embedded documents 
    var album = artist.albums.findOne({ name: 'Pretty Hate Machine' });
    album.songs.sortAsc('trackNum');
    
});