【问题标题】:How to show suggestions in MongoDB find()如何在 MongoDB find() 中显示建议
【发布时间】:2021-06-28 05:40:40
【问题描述】:

我正在使用 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.js database mongodb mongoose mongodb-query


    【解决方案1】:

    演示 - https://mongoplayground.net/p/HNq6Vno-FPM

    $or

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

    【讨论】:

    • 这很好用,但是当我使用 find() 它查询整个文档时,我只想在结果中显示用户名、名字、姓氏。用户从此列表中选择后,我稍后会查询整个文档
    • @NithinSai 更新答案添加投影。
    • 嗯,这行得通!我不确定它是否真的减少了资源的使用,因为我是新手,但它确实有效。谢谢!我以为我必须使用聚合和自动完成docs.atlas.mongodb.com/reference/atlas-search/autocomplete
    猜你喜欢
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    相关资源
    最近更新 更多