如果你不想使用正则表达式来实现Mongoose局部字段搜索,你可以使用Mongoose的$regex运算符和$or运算符进行搜索。
下面是一个使用Mongoose实现局部字段搜索的示例代码:
首先,定义一个Mongoose模式(Schema):
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: String,
description: String,
price: Number
});
const Product = mongoose.model('Product', productSchema);
然后,编写一个搜索函数,该函数接收一个关键字作为参数,并使用$or运算符和$regex运算符来进行模糊搜索:
async function searchProducts(keyword) {
const regex = new RegExp(keyword, 'i');
const products = await Product.find({
$or: [
{ name: { $regex: regex } },
{ description: { $regex: regex } }
]
});
return products;
}
最后,调用搜索函数并打印结果:
searchProducts('apple')
.then(products => console.log(products))
.catch(error => console.error(error));
在上面的示例中,我们使用了$regex运算符来创建一个正则表达式对象,以便在搜索过程中忽略大小写。然后,我们使用$or运算符来指定在'name'字段和'description'字段上进行模糊搜索。
上一篇:不使用正则表达式的单词模式
下一篇:不使用正则表达式获取端口