Javascript Mongoose iterate and post order find()结果数组
基于Javascript Mongoose iterate and post order find()结果数组,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,基于id列表,我需要获取mongoose数据,并按照给定id的相同顺序构建返回数组。不存在的字段必须填入null。这是我的密码: export const getByIds = async ids => { let results = await Customers.find({ _id: { $in: ids }, deletedAt: null }).exec(); let rows = ids.map(id => { let found = r
id
列表,我需要获取mongoose数据,并按照给定id
的相同顺序构建返回数组。不存在的字段必须填入null
。这是我的密码:
export const getByIds = async ids => {
let results = await Customers.find({ _id: { $in: ids }, deletedAt: null }).exec();
let rows = ids.map(id => {
let found = results.find(item => {
return item._id.equals(id);
});
return found ? found : null;
});
return rows;
};
无论ID是否存在,每次调用函数都会得到一个null数组。我做错了什么?试试这个代码
let rows = ids.filter(id => {
let found = results.filter(item => {
if(item._id == id){
return item;
}else{
return false
}
});
return found ? found : null;
});
您是否应该使用findone或findbyid来查找特定项?\您的id是由MongoDB创建的特定id您应该指定由MongoDB findbyid()生成的查找您使用的id您是否在
结果中获得了预期客户
?从mongodb获取数据时,id作为objectId返回,而ids数组将包含需要更改返回项的id字符串数组。\u id.equals(id);返回(item.\u id).toString()等于(id);为了匹配它们是的,我在结果中得到了预期的客户;我没有使用findOne或findById,因为ids
变量是一个id数组(我希望一次得到几个文档)。