无法使用位置运算符

时间:2020-08-19 09:02:30

标签: mongodb mongoose

在嵌套数组中使用library(shiny) # FAKE DATAFRAME data <- reactive( data.frame( group = sample(c("A", "B"), 100, replace = TRUE), var1 = round(runif(100, min = 0, max = 100), 0), var2 = sample(c("A", "B"), 100, replace = TRUE) ) ) # USER INTERFACE ui <- fluidPage( tableOutput("table1") ) # SERVER server <- function(input, output) { output$table1 <- renderTable({ table(data()$group, data()$var2) }) } # START APP shinyApp(ui = ui, server = server) 时,在mongodb / mongoose中使用$[<identifier>]运算符会遇到麻烦。使用它时,它似乎对我不起作用,item.nModified始终为0,并且数据库中未更新任何内容。知道我在做什么错吗?

$set

如果我删除arrayFilters对象并使用await Product.update( {productName: product.productName}, { "$set": { "stores.$[index].trackingUrl": 'url', } }, { "arrayFilters": [ { "index": 0 }, ] }, ).then((item) => { console.log("Updated", item.nModified); }); ,而没有操作符,它将正确更新值。

如果我使用"stores.$[].trackingUrl": 'url',并离开arrayFilters,则会出现此错误

"stores.$[].trackingUrl": 'url'

如果我将MongoError: The array filter for identifier 'index' was not used in the update { $set: { stores.$[].trackingUrl: "url" } } 中的0更改为1,则会出现此错误。目前在stores数组中只有1个对象,因此它在此处崩溃也就不足为奇了。

{"index": 0}

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,
    },
  ],
});

1 个答案:

答案 0 :(得分:1)

the filtered positional operator的标识符部分用于根据子文档的字段指定条件。您的示例不起作用,因为没有商店的索引字段。

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

{ $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); 
        });
相关问题