我们有两种型号:
- 用户
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.
您能帮助我们吗?如何实现这一目标?
最佳答案
您可以首先对车辆模型运行查询以获取名称为粉色的所有车辆
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不为空,则vehicles[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:}}
]})
关于node.js - 如何从 Mongoose 的填充模型中查找文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57488375/