首页 > 解决方案 > 无法使用位置运算符

问题描述

在嵌套数组中$[<identifier>]使用 mongodb/mongoose中的运算符时遇到问题。$set使用它时似乎对我不起作用, item.nModified 始终为 0 并且数据库中没有任何更新。知道我做错了什么吗?

await Product.update(
          {productName: product.productName},
          { "$set": {
              "stores.$[index].trackingUrl": 'url',
            } },
          { "arrayFilters": [
              { "index": 0 },
            ] },

        ).then((item) => {
          console.log("Updated", item.nModified); 
        });

如果我删除 arrayFilters 对象并使用"stores.$[].trackingUrl": 'url', 没有运算符,它将正确更新值。

如果我使用"stores.$[].trackingUrl": 'url', 并离开 arrayFilters 我得到这个错误

MongoError: The array filter for identifier 'index' was not used in the update { $set: { stores.$[].trackingUrl: "url" } }

如果我将其更改01出现{"index": 0}此错误。我目前在 stores 数组中只有 1 个对象,所以它在这里崩溃也就不足为奇了。

 CastError: Cast to embedded failed for value "1" at path "stores"

架构Product

const ProductSchema = new Schema({
  ean: String,
  productName: String,
  mainCategory: String,
  subCategory: String,
  group: String,
  subSubCategory: String,
  lowestPrice: Number,
  isPopular: Boolean,
  description: String,
  keyword: String,

  stores: [
    {
      name: String,
      programId: Number,
      productPrice: Number,
      productUrl: String,
      imageUrl: String,
      sku: String,
      currency: String,
      manufacturerArticleNumber: String,
      manufacturer: String,
      oldPrice: Number,
      shipping: Number,
      inStock: Boolean,
      market: String,
      approvalStatus: Number,
      trackingUrl: String,
      productDescription: String,
      timestamp: String,
    },
  ],
});

一份文件

{ _id: 5f3bf084fa56743527344454,
  ean: '000',
  productName: 'name',
  lowestPrice: 5,
  mainCategory: 'Leksaker',
  group: 'Leksaker',
  subCategory: 'Djur',
  subSubCategory: '',
  stores:
   [ { _id: 5f3cc819d28fc65d915016bc,
       name: 'Stor & Liten',
       programId: 0,
       productPrice: 359,
       productUrl: 'https://www.storochliten.se/papo-kaprosuchus',
       imageUrl:
        'https://media.storochliten.se/product-images/XL//papo-kaprosuchus-0.jpg',
       sku: '317969',
       currency: 'SEK',
       manufacturerArticleNumber: 'P55056',
       manufacturer: 'Papo',
       oldPrice: 359,
       shipping: 0,
       inStock: true,
       market: 'SE',
       trackingUrl: '', //expect to insert "url" here
       productDescription:'text',
       timestamp: '2020-08-19T06:35:05.595Z' } ],

}

标签: mongodbmongoose

解决方案


过滤位置运算符的标识符部分用于指定基于子文档字段的条件。您的示例不起作用,因为没有用于存储的索引字段。

如果你想更新第一个元素,你可以简单地使用点符号:

{ $set: { 'stores.0.trackingUrl': 'url' }

如果您需要store通过任何字段进行识别,您可以尝试使用_id(或任何其他现有字段):

await Product.update(
        {productName: product.productName},
        { "$set": {
            "stores.$[store].trackingUrl": 'url',
            } },
        { "arrayFilters": [
            { "store._id": 5f3cc819d28fc65d915016bc },
            ] },

        ).then((item) => {
        console.log("Updated", item.nModified); 
        });

推荐阅读