mongodb Mongoose无法通过更新子文档在架构中找到路径“${filterPath

dl5txlt9  于 2022-12-26  发布在  Go
关注(0)|答案(1)|浏览(69)

在此项目对象中:

{
    "items": [
        {
            "_id": "63a48f12a9731cfd8a64b0b1",
            "item_name": "addidas shoes",
            "__v": 0,
            "rating": [
                {
                    "_id": "63a48fd51fb70775d216eb87",
                    "rate": 1,
                    "user_id": "6398a1a157d6146413b23b43"
                }
            ]
        }
    ]
}

我尝试更新rating属性,如果其中已经存在user_id,否则,向其中添加一个新对象。

const addRating = async (req, res) => {
  const { rate, user_id, item_id } = req.body;
  // item_id = 63a48f12a9731cfd8a64b0b1 user_id = 6398a1a157d6146413b23b43 rate = 6

  // Adding ratings to the selected item
  const test = await itemDB.item.updateOne(
    { _id: item_id, rating: { user_id: user_id } },
    { $push: { "items.rating.$[i].rate": rate } },
    { arrayFilters: [{ "i.user_id": user_id }], upsert: true }
  );
  console.log(test);
  res.json({ message: "success" });
};

我想在rating属性中更改一些内容,所以我如上所述设置了过滤器,但在到达端点时,它给了我这个错误:

\node_modules\mongoose\lib\helpers\update\castArrayFilters.js:74
        throw new Error(`Could not find path "${filterPath}" in schema`);
              ^

Error: Could not find path "items.rating.0.user_id" in schema

这是我的项目方案:

const mongoose = require("mongoose");
const RateSchema = mongoose.Schema({
  rate: {
    type: Number,
    required: true,
  },
  user_id: {
    type: mongoose.ObjectId,
  },
  item_id: {
    type: mongoose.ObjectId,
  },
});

const ItemSchema = mongoose.Schema({
  item_name: {
    type: String,
    required: true,
  },
  rating: {
    type: [RateSchema],
  },
});

module.exports = mongoose.model("Items", ItemSchema);
7bsow1i6

7bsow1i61#

在对rating应用数组过滤器时,似乎没有注意到items也是一个数组。
尝试使用全位置运算符,如下所示:

{ $push: { "items.$[].rating.$[i].rate": rate } }

相关问题