我是 MongoDB 的新手,正在尝试对数据库中的数组重新排序。
这是架构:
headline: String,
Galleryslides: [{type: ObjectId, ref: 'Galleryslide'}],
这是我正在使用的逻辑。顺便说一下,correctOrder 是一个数组,其中包含数据库的新 ID 顺序。
Gallery.findById(req.params.galleryId, function(err, gallery) {
var newArr = [];
req.body.ids.forEach(function(id, index) {
newArr[index] = Galleryslides.find({"_id" : id});
});
gallery.Galleryslides = newArr;
gallery.save(function() {
res.json({status: 'ok'});
});
});
运行时,没有任何反应——数据库中数组的顺序没有改变。你知道更好的方法吗?
最佳答案
在mongodb中,记录按natural order排序.您应该按照插入的相同顺序获取它们,但不能保证如此。
就像文档说的那样:
This ordering is an internal implementation feature, and you should not rely on any particular structure within it.
如果你想按 _id
字段排序,你可以这样做(它将按 _id 索引排序):
Gallery.find().sort({ "_id": 1 })
关于javascript - 在 MongoDB 中重新排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39261093/