如何在mongoDB或mongoose中进行部分搜索?

如何在mongoDB或mongoose中进行部分搜索?,mongodb,mongoose,mongoose-schema,Mongodb,Mongoose,Mongoose Schema,我的用户模型模式是 const userSchema = new mongoose.Schema( { firstname: { type: String, required: true, trim: true }, lastname: { type: String, trim: true }, email: { type: String, unique: true, required: true,

我的用户模型模式是

const userSchema = new mongoose.Schema(
  {
  firstname: {
    type: String,
    required: true,
    trim: true
  },
  lastname: {
    type: String,
    trim: true
  },
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true,
    lowercase: true
  },
  password: {
    type: String
  },
  phone: {
    type: Number,
    trim: true,
    unique: true,
    sparse: true
  }
});
我还为多个字段的文本搜索建立了索引FirstName、lastname、email

userSchema.index({firstname: 'text', lastname: 'text', email: 'text'}, {default_language: 'none'});
现在我在用户中搜索“alex”-

const result = await User.find({$text : { $search: 'alex' }}).skip(1).limit(1);
当我搜索整个单词如“alex”时,我得到了结果,但是如果我搜索“al”,那么我什么也得不到

所以我想在搜索像‘al’这样的部分单词时得到结果,然后在结果中也得到了‘alex’记录

正如有人建议的那样

let searchText = "l";

let condition = { $or: [{ firstname: new RegExp("^" + searchText, "i") }, { lastname: new RegExp("^" + searchText, "i") }] }

const result = await User.find(condition);
它工作正常,但仍然没有涵盖一个案例,比如我有一个名为“alex”的文档,如果我搜索“le”,我也会得到这个文档。

您可以这样使用:

let searchText = "al";

let condition = { $or: [{ firstname: new RegExp("^" + searchText, "i") }, { lastname: new RegExp("^" + searchText, "i") }] }

const result = await User.find(contition).skip(1).limit(1);

这是否回答了您的问题,但如何进行多字段搜索,就像我想在一些字段中搜索搜索搜索查询'al'“firstname,lastname,email.check了解新的beta部分文本搜索功能。它工作正常,但有一次我没有得到结果,比如用户名是“alex”,如果我搜索“le”,我什么也得不到。