首页 > 解决方案 > 如何在 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 堆栈,如何在前端查询文档并显示自动完成的建议?

标签: node.jsdatabasemongodbmongoosemongodb-query

解决方案


演示 - 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" } });

推荐阅读