node.js - 如何在猫鼬中从填充模型中查找文本?
问题描述
我们有两个模型:
- 用户
const userSchema = new mongoose.Schema({
name: {
type: String
},
email: {
type: String
},
vehicleId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'vehicle'
}
})
- 车辆
const vehicleSchema = new mongoose.Schema({
name: {
type: String
},
color: {
type: String
}
})
现在,我们必须从用户(姓名,电子邮件)和车辆(姓名,颜色)中找到用户输入
- If user search "pink" then we have to find that if any user has with name, email or them vehicle include "pink" keyword or not.
- If string match from reference model then we have to return whole record.
你能帮助我们,如何实现这一目标?
解决方案
您可以先在 Vehicle 模型上运行查询,以获取名称为 pink 的所有车辆
let vehicleIds=await Model.Vehicle.aggregate([
{$match:{$or:[
{name:{$regex:"pink",$options:"i"}},
{color:{$regex:"pink",$options:"i"}
]}},
{$group:{_id:null,ids:{$push:"$_id"}}}
])
此处如果 vehicleIds 不为空,则车辆 [0].ids 将具有名称或颜色为粉红色的 vehcileIds
let vehcileIds=[]
if(vehicles.length) vehcileIds=vehicles[0].ids
在上述查询运行后,在用户模型中运行另一个查询
let users= await Models.User.find({$or:[
{name:{$regex:"pink",$options:"i"}},
{email:{$regex:"pink",$options:"i"}
{vehicleId:{$in:}}
]})
推荐阅读
- swift - Extract Reality Composer scene for ARQuickLook
- python - slackclient python - 异步 RTM 客户端
- visual-studio - Cmake 在 Windows 中显示“PYTHON_LIBRARY-NOTFOUND”
- angular - 如何在 PrimeNG 表中单独使用分页器并显示页面信息?
- javascript - 如何更改轴 Chart.js 的显示
- android - LiveData observable 如何异步处理 Room 查询?
- node.js - 在 execute_payment_json 中获取可变金额
- kotlin - 无法使用 String 类型的 accountToPay (accountID) 更新SettlementMethod
- jquery - 使用 Scrollify 时,我得到 Scrollify is not a function 错误
- xml - 如何根据每个 XML 标记中存在的特定属性对多级 XML 进行排序?