0

Suppose I have 2 Schema's in Mongoose that look like this:

var movieSchema = mongoose.Schema({
    name: String,
    type: String
});

var moviePlaylistSchema = mongoose.Schema({
    name: String,
    movies: [{type: mongoose.Schema.Types.ObjectId, ref: 'Movie'}]

});

var Movie = mongoose.model('Movie', movieSchema);
var MoviePlaylist = mongoose.model('MoviePlaylist', moviePlaylistSchema);

If a query was made along the following lines:

MoviePlaylist.find({}).populate('movies').exec(function(err, res) {
    if (err) console.log('err', err);
    else {
        console.log('res', res);
        res.forEach(function(elem, index) {
            console.log('elem.name', elem.name);
        });
    }
});

Would the order of the elements in the array be maintained? The objective here is to allow the user to maintain a playlist order of their movies. If, when the "populate" method fires, the array order of Movie object Ids is not maintained, then this will not serve my purpose. Hence thought I'd ask someone who is more knowledgeable in this area.

If this works, then I have another task which is allowing the user to change the order of movies in the playlist, which should be straight forward by allowing the movie object id index to be swapped in the array.

Thanks for your help in advance.

Neil D'Souza
  • 236
  • 3
  • 7

1 Answers1

0

MongoDB will keep the order of the array, much like an array in any programming language.

You can view the BSON/JSON spec for reference which highlights that the array must contain integer values for keys, and be maintained in ascending numerical order.

Additionally, the Mongoose populate on an array works by calling Model.populate via forEach on each element of the array. This modifies the array in place, hence the order is preserved. You can see the relevant source code here.

snozza
  • 2,123
  • 14
  • 17
  • Thx. The question is - does the mongoose populate method keep the raw array order. However I checked with a friend - and he gave me this link to the populate code for mongoose. https://github.com/Automattic/mongoose/blob/master/lib/model.js#L2342 . He also gave me a link to stack overflow - that $in does not guarantee the order of the array elements - http://stackoverflow.com/questions/22797768/does-mongodbs-in-clause-guarantee-order . However, reading the code on the github source page - and I can see a hint of maintaining Item order - see line 2298 to 2317. Can someone verify – Neil D'Souza Sep 03 '15 at 08:16