我有两个模型,每个模型都像这样相互关联
const InvoiceSchema = new Schema({
generate_id : {
type : String,
required : true,
unique : true
},
customer : {
type: Schema.Types.ObjectId,
ref: 'Customer'
},
});
const Invoice = mongoose.model('Invoice', InvoiceSchema);
module.exports = Invoice ;
const CustomerSchema = new Schema({
name : {
type : String,
required : true,
},
mobile_number : {
type : String,
required:true,
unique:true
},
invoices : [
{
type: Schema.Types.ObjectId,
ref: 'Invoice'
}
]
});
const Customer = mongoose.model('Customer', CustomerSchema);
module.exports = Customer ;
现在在我的应用程序中,当我在其上键入内容时,我有搜索输入,事件 keyup 会像这样自动运行查询
来自JS文件
document.querySelector('.md-ctt-inp-search').addEventListener('keyup', ()=>{
const str = document.querySelector('.md-ctt-inp-search').value;
fetch(`/getres/${str}`)
.then(response =>response.json())
.then(data => {
console.log(data);
});
});
来自节点 js (/getres/str)
exports.getRes = async (req, res, next)=> {
const invoice = await Invoice.find(
{ 'generate_id': new RegExp(req.params.str, 'i') },
).populate({
path: 'Invoice',
match: $or: [
{ 'name': new RegExp(req.params.str, 'i') },
{ 'mobile_number': new RegExp(req.params.str, 'i') }
]
});
res.json(invoice);
});
因此,当我在输入搜索上键入时,事件 keyup 将运行查询(自动完成搜索)。 我想要关键字 (str) 搜索来自 Invoice 模型的字段 generate_id 或来自 Customer 模型的 name 或 mobile_number。
所以无论我输入什么,这个关键字都会查找这 3 个字段(generate_id、name 和手机号码)