【发布时间】:2018-03-22 18:09:18
【问题描述】:
使用提供的查询考虑这个 NodeJS 路由:
app.post("/api/test", async function(req, res) {
const findTags = ["banana", "produce", "yellow", "organic", "fruit"];
Product.find({
tags: {
$size: findTags.length,
$in: findTags
}
})
.sort({ date: "descending" })
.limit(20)
.exec(function(err, docs) {
console.log("Query found these products: ");
console.log(docs);
});
});
在我的 MongoDB 中,我有以下两个条目:
{
name: "Banana",
"tags": [
"banana",
" produce",
" yellow",
" organic",
" fruit"
]
},
{
name: "Blueberry",
"tags": [
"organic",
" produce",
" blue",
" blueberries",
" fruit"
]
}
我希望查询只返回 Banana 返回
实际结果: Banana 和 Blueberry 均被退回。
所以我尝试用$all 替换$in,我得到的只是一个空数组。意味着它没有找到任何东西!这怎么可能?
我正在尝试做的事情:我想找到所有Products 具有至少所有findTags。产品有 100 个以上的标签也没关系,只要它有我要找的所有标签。
我将如何更改我的查询以实现这一点?
【问题讨论】:
-
$all不起作用,因为标签中有空格。 -
叮叮叮。我想就是这样!!
-
@Phillip 在数据库条目中,每个字符串之前都有空格。
标签: node.js database mongodb mongoose mongoose-schema