【问题标题】:Which is the equivalent in Mongoose of this MongoDb query db.collection.find( { tags: { $all: [some elements in the array] } } )这在 Mongoose 中相当于 MongoDb 查询 db.collection.find( { tags: { $all: [some elements in the array] } } )
【发布时间】:2021-11-04 21:17:12
【问题描述】:

我正在尝试在 Mongoose 中找到与此 MongoDB 查询 db.inventory.find( { tags: { $all: ["red", "blank"]}}) 的等效项。我在 Mongoose Model.find({'field': { $in: array name }) 中找到了这个,但它给了我作为结果文档,其中包含文档中数组中的所有元素以及与数组中至少一个元素匹配的文档。

这是我用来展示具有特定专业的工匠的代码:

显示工匠简介路线

app.post('/artisanprofile', function(req, res){
  const profile = [];
  const result = req.body.search;
  console.log(result);
  console.log(typeof result);
  const specialities = result.split(" ");
  console.log(specialities);
  Artisan.find({
    'speciality': { $in: specialities }
}, function(err, profiles) {
  if(err){
    console.log(err);
  }
  else{
    console.log(profiles);
  }
});
});

我要查找的文档是具有特长 test 和 test1 的文档,但我得到了所有文档,其中至少包含数组 specialties 中的一个元素传递给查询。

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    试试看 使用 and 和 specialities 的每个元素使用 $in

    app.post('/artisanprofile', function(req, res){
      const profile = [];
      const result = req.body.search;
      console.log(result);
      console.log(typeof result);
      const specialities = result.split(" ");
      console.log(specialities);
      var andObj = {}
      var andArr = []
      specialities.forEach(item=>{
          var itemArr = []
          itemArr.push(item)
          andObj['$in'] :itemArr
          andArr.push({speciality:andObj})
          andObj = {}
      })
      Artisan.find({
        $and : andArr
    }, function(err, profiles) {
      if(err){
        console.log(err);
      }
      else{
        console.log(profiles);
      }
    });
    });
    

    【讨论】:

      猜你喜欢
      • 2022-12-26
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2017-11-14
      • 2019-06-27
      • 2015-02-28
      • 2022-07-22
      相关资源
      最近更新 更多