Luc*_*dro 5 mongoose mongodb node.js mongodb-query
我需要在数组元素内执行文本搜索。是否可以?
在 Node.js 中使用 Mongoose,我的 userSchema 如下所示:
{
_id: "123456",
name: "Lucas"
items: [
{ title: "Shoes", description: "Very nice shoes"},
{ title: "Pants", description: "Great pants!"}
]
}
Run Code Online (Sandbox Code Playgroud)
我试图添加这样的索引:
userSchema.index({ "items.title": "text", "items.description": "text" });
Run Code Online (Sandbox Code Playgroud)
但以下查询不返回任何内容:
User.find({ $text: { $search: "Shoes" }});
Run Code Online (Sandbox Code Playgroud)
mongoose 不是索引管理解决方案。所以不要依赖mongoose来创建索引。他们甚至在FAQ 的文档中声明了这一点。
在生产环境中,您应该使用 MongoDB shell 创建索引,而不是依赖 mongoose 来为您创建索引。
因此,您需要做的就是在 mongodb shell 中创建文本索引。如果集合名称与您不同,users
您还需要在下面进行更改。
db.users.createIndex(
{
"items.title": "text",
"items.description": "text",
}
)
Run Code Online (Sandbox Code Playgroud)