node.js - 如何在 MongoDB find() 中显示建议
问题描述
我正在使用 mongoDB Atlas 来存储一些数据。集合就像,
var User = new Schema({
firstname: {
type: String,
default: ''
},
lastname: {
type: String,
default: ''
}
}, {
timestamps: true
});
但我使用 Passport 进行身份验证,用户名和密码由它处理。
按用户名搜索用户时,我想显示具有匹配字符的用户名列表。喜欢,自动完成建议。
我意识到我必须以某种方式使用正则表达式来实现这一点,但我不知道怎么做!目前,我正在这样做,
router.post('/search', corsWithOptions, (req, res, next) => {
User.findByUsername(req.body.username).then(user => {
console.log(user);
res.json(user)
})
})
但在整个用户名可用之前,此方法返回 null。这里,findByUsername
是 Passport 中的一个方法,需要 2 个参数(用户名,selectHashSaltFields)。
这个我也试过
User.find({
$or: [
{
username: { '$regex': '.*' + req.body.search, $options: 'i' },
firstname: { '$regex': '.*' + req.body.search, $options: 'i' },
lastname: { '$regex': '.*' + req.body.search, $options: 'i' }
}
]
}).then(user => {
console.log(user)
})
这将返回一个空列表,即使值存在
这是一个 MERN 堆栈,如何在前端查询文档并显示自动完成的建议?
解决方案
演示 - https://mongoplayground.net/p/HNq6Vno-FPM
db.collection.find({
$or: [
{ username: { "$regex": ".*abc", "$options": "i" } },
{ firstname: { "$regex": ".*abc", "$options": "i" } },
{ lastname: { "$regex": ".*abc", "$options": "i" } }
]
}, { username: 1, lastname: 1, firstname: 1 }) // project only if you want ignore _id also use _id: 0
创建Text Indexes
并使用$text进行搜索。
db.user.createIndex({ username: "text", firstname : "text", lastname : "text" });
db.user.find({ $text: { $search: "abc" } } );
db.user.find({ $text: { $search: "/TuShAr/i" } });
推荐阅读
- sql - 根据特定条件选择要在 FROM 子句中使用的表
- android - 如何使用where子句删除firestore数据库中的集合中的文档?
- c - 使用 dup 到文件的 C 标准输出
- java - Java 8,IntStream BaseStream,对索引的多重引用
- r - 连接来自 2 个数据源的数据以组合为一个
- javascript - 我的独特功能不适用于数组?
- c# - 当客户端意外关闭时,Networkstream Read 会引发错误
- cuda - 将 Directx 12 纹理导入 cuda 表面:列好,行拧紧
- javascript - 使用 Promise 和异步我哪里出错了?
- javascript - Javascript 500 元素数组