【问题标题】:mongoDB find, update and pull in One QuerymongoDB 查找、更新和拉入一个查询
【发布时间】:2018-04-19 17:12:29
【问题描述】:

我想做所有从集合中查找数据然后想要更新一些字段以及取决于想要清空数组的操作。

const addCityFilter = (req, res) => {
  if (req.body.aCities === "") {
    res.status(409).jsonp({ message: adminMessages.err_fill_val_properly });
    return false;
  } else {
    var Cities = req.body.aCities.split(","); // It will make array of Cities
    const filterType = { "geoGraphicalFilter.filterType": "cities", "geoGraphicalFilter.countries": [], "geoGraphicalFilter.aCoordinates": [] };
    /** While using $addToset it ensure that to not add Duplicate Value
     * $each will add all values in array
     */
    huntingModel
      .update(
        {
          _id: req.body.id,
        },
        {
          $addToSet: {
            "geoGraphicalFilter.cities": { $each: Cities }
          }
        },
        {$set:{filterType}},
      ).then(function(data) {
        res.status(200).jsonp({
          message: adminMessages.succ_cityFilter_added
        });
      });
  }
};

收藏

geoGraphicalFilter: {
    filterType: {
      type:String,
      enum: ["countries", "cities", "polygons"],
      default: "countries"
    },
    countries: { type: Array },
    cities: { type: Array },
    aCoordinates: [
      {
        polygons: { type: Array }
      }
    ]
  }

但结果,唯一的城市数组正在更新。 filterType 没有变化。

【问题讨论】:

  • 因为那是{ "$addToSet": { ... }, "$set": { ... } }。你的错误语法是{ "$addToSet: {.. } }, { "$set": { ... } }。请查看.update() 签名update(<query>,<update>,<options>)。所以<update>一个文档,您可以在其中放入单独的文档

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

您似乎将filterType$set 作为选项参数而不是更新参数传递。

huntingModel
  .update(
    {
      _id: req.body.id,
    },
    {
      $addToSet: {
        "geoGraphicalFilter.cities": { $each: Cities }
      },
      $set: {
        filterType
      }
    }
  ).then(function(data) {
    res.status(200).jsonp({
      message: adminMessages.succ_cityFilter_added
    });
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2014-02-09
    • 1970-01-01
    相关资源
    最近更新 更多