Node.js Mongo$in/$all未按预期工作

Node.js Mongo$in/$all未按预期工作,node.js,database,mongodb,mongoose,mongoose-schema,Node.js,Database,Mongodb,Mongoose,Mongoose Schema,使用提供的查询考虑此NodeJS路由: app.post("/api/test", async function(req, res) { const findTags = ["banana", "produce", "yellow", "organic", "fruit"]; Product.find({ tags: { $size: findTags.length, $in: findTags } })

使用提供的查询考虑此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
back

实际结果:香蕉和蓝莓都被返回

所以我试着用
$all
替换
$in
中的
$in,得到的只是一个空数组。意思是它什么也没找到!这怎么可能

我想做的:我想找到所有
产品
,这些产品至少包含所有
findTags
。如果产品有100多个标签就可以了,只要它有我要找的所有标签


如何更改查询以实现此目的?

您必须这样编写查询。您还必须从数据库中删除空格。或者用空格查询标签

var tagsArr = ["banana", "produce", "yellow", "organic", "fruit"];
var query = {tags: {$all: tagsArr } };

Product.find(query).sort({ date: "descending" })
  .limit(20)
  .exec(function(err, docs) {
    console.log("Query found these products: ");
    console.log(docs);
  });

$all
不适用于您,因为文档中的
标记与查询中的
标记不匹配。

一些
标记
在文档中包含尾随空格(例如
product

您刚刚将查询保存到变量中,并添加了不需要的“name”。这并不能解决您需要从db集合中的标记中删除空格的问题。然后点击查询。
$all
不起作用,因为标记中有空格。叮叮叮。我想就是这样@Phillip在DB条目中,每个字符串前都有空格。哈哈哈,我的标签中有空格。。。天啊