我有一系列Mongoose ID'如下:
if let data = postJson.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
}
catch {
print(error.localizedDescription)
}
}
当我调用Mongoose函数来获取与这些id匹配的子文档时,对象将按照它们在数据库中的查找顺序返回给我。我可以根据上述' ID的顺序对这些进行重新排序。阵列
返回给我的数据如下:
var ids =[
mongoose.Types.ObjectId('58c2871414cd3d209abf4fc1'),
mongoose.Types.ObjectId('58c2871414cd3d209abf4fc0'),
mongoose.Types.ObjectId('58c2871414cd3d209abf5fc0')
];
有没有办法根据原始数组重新排序这些?请注意,数组中返回了两个_id,它是我需要订购的position子文档的id。如果有人能提供帮助那就太棒了!
修改
My Node.js功能如下:
[ { _id: 58c2871414cd3d209abf5fc9,
companyname: 'Dell',
position:
{ _id: 58c2871414cd3d209abf5fc0,
title: 'Software Engineer',
location: 'Waterford',
start: 'May 2017',
term: 6,
description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },
{ _id: 58ca9fd6588205e9c8f01431,
companyname: 'Google',
position:
{ _id: 58c2871414cd3d209abf4fc0,
title: 'Software Engineer',
location: 'Waterford',
start: 'May 2017',
term: 6,
description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },
{ _id: 58ca9fd6588205e9c8f01431,
companyname: 'Google',
position:
{ _id: 58c2871414cd3d209abf4fc1,
title: 'Software Engineer',
location: 'Waterford',
start: 'June 2017',
term: 12,
description: ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis erat vitae dsit amet, consectetur adipiscing elit. Vivamus quis erat vitae dolor tempus euismod non in mi' },
]
登录控制台:
var ids =[mongoose.Types.ObjectId('58c2871414cd3d209abf4fc0'), mongoose.Types.ObjectId('58c2871414cd3d209abf4fc1'), mongoose.Types.ObjectId('58c2871414cd3d209abf5fc0')];
User.aggregate( { $unwind : "$position" },
{ $match: { "position._id": {
$in: ids }
}
}
, function(err, results){
// results.sort((a, b) => {
console.log(a+" "+b);
// return ids.indexOf(mongoose.Types.ObjectId(a.position._id))
// - ids.indexOf(mongoose.Types.ObjectId(b.position._id))
// })
res.send({results:results});
});
});
答案 0 :(得分:0)
您可以将Array.prototype.sort()与比较功能一起使用,比较功能使用Array.prototype.indexOf()查找ids
中每个元素的索引,并为其element.postion.id
。
以下是代码:
data.sort((a, b) => {
return ids.indexOf(a.position._id) - ids.indexOf(b.position._id)
})
我使用_id
作为字符串,您必须将其更改为mongoose.Types.ObjectId()
我认为它就是这样做的
data.sort((a, b) => {
return ids.indexOf(mongoose.Types.ObjectId(a.position._id)) - ids.indexOf(mongoose.Types.ObjectId(b.position._id))
})