查询嵌套对象mongoose



我正在尝试重现"像";猫鼬中的行为,通过搜索用户名类似"的所有元素;abcd"这个函数返回了我用馈送db.find函数的结果

const rgx = (pattern) => new RegExp(`.*${pattern}.*`);
const orFilter = [];
fields.forEach((field) => {
if (field.includes('.')) {
const [parent, child] = field.split('.');
orFilter.push({
[parent]: { [child]: { $regex: rgx(searchText), $options: 'i' } },
});
} else {
orFilter.push({ [field]: { $regex: rgx(searchText), $options: 'i' } });
}
});
return { $or: orFilter };
  • 条目1:[城市','zipCode']工作正常

  • 条目2:['city','zipCode','user.name']不起作用。

我收到以下消息*CastError:值的强制转换为ObjectId失败{name:{'$regex':/.abc./,'$options':'i'}}*

我的问题的解决方案是通过使用聚合访问找到的https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate/!我试图访问存储在另一个表user.name中的值

最新更新