MongoDb子文档数组填充(通过Mongoose ORM):当填充被调用时,它是否保持数组顺序

时间:2022-05-26 21:26:40

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

假设我有2个Mongoose的模式是这样的

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.

是否会维护数组中元素的顺序?这里的目标是允许用户维护他们电影的播放列表顺序。如果“populate”方法触发时,电影对象id的数组顺序没有被维护,那么这就不能满足我的目的了。因此我想问一个在这方面更有见识的人。

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.

如果这是可行的,那么我还有另外一个任务,就是允许用户改变播放列表中的电影顺序,这应该是直接的,允许在数组中交换电影对象id索引。

Thanks for your help in advance.

提前谢谢你的帮助。

1 个解决方案

#1


0  

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

MongoDB将保持数组的顺序,就像任何编程语言中的数组一样。

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.

您可以查看BSON/JSON规范以获得参考,该规范强调数组必须包含键的整数值,并按升序进行维护。

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.

此外,Mongoose通过调用模型来填充数组。通过forEach填充数组的每个元素。这将对数组进行修改,从而保留该顺序。您可以在这里看到相关的源代码。

#1


0  

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

MongoDB将保持数组的顺序,就像任何编程语言中的数组一样。

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.

您可以查看BSON/JSON规范以获得参考,该规范强调数组必须包含键的整数值,并按升序进行维护。

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.

此外,Mongoose通过调用模型来填充数组。通过forEach填充数组的每个元素。这将对数组进行修改,从而保留该顺序。您可以在这里看到相关的源代码。