代码之家  ›  专栏  ›  技术社区  ›  ASX

流星收集:使用阵列插入

  •  0
  • ASX  · 技术社区  · 8 年前

    我有这样一个模式(简化):

    StatusObject = new SimpleSchema({
       statusArray: [statusSchema]
    });
    

    哪里 statusSchema

    {
        topicId:{
            type: String,
            optional: true
        },
        someInfo:{
            type: Number,
            optional: true,
            decimal: true
        },
        otherInfo:{
            type: Number,
            optional: true
        }
    }
    

    upsert -使用以下meteor方法代码:

    var upsertResult = BasicInfo.update({
      userId: this.userId, 
      statusArray: {
        $elemMatch: { topicId : newStatus.topicId }
      }
    }, { 
      $set: {
        "statusArray.$.topicId": newStatus.topicId,
        "statusArray.$.someInfo": newStatus.someInfo,
        "statusArray.$.otherInfo": newStatus.otherInfo
      }         
    }, {
      multi: true,
      upsert: true
    });
    

    但我不断地发现一个错误: statusArray must be an array $ ,我要确保它被识别为数组?我错过了什么?

    2 回复  |  直到 8 年前
        1
  •  0
  •   Styx    8 年前

    userId 并修改其 statusArray 使用以下场景之一的阵列:

    • 使用特定 topicId 价值
    • topicId公司

    不幸的是,您无法仅使用一个DB查询来实现它,因此它应该是这样的:

    // try to update record
    const updateResult = BasicInfo.update({
      userId: this.userId, 
      'statusArray.topicId': newStatus.topicId
    }, { 
      $set: {
        "statusArray.$": newStatus
      }         
    });
    
    if (!updateResult) {
      // insert new record to array or create new document
      BasicInfo.update({
        userId: this.userId
      }, {
        $push: {
          statusArray: newStatus
        },
        $setOnInsert: {
          // other needed fields
        }
      }, {
        upsert: true
      });
    }
    
        2
  •  -1
  •   Mikkel    8 年前

    您的代码将StatusArray视为一个对象,

    currentRecord

    newStatusArray = currentRecord.statusArray
    newStatusArray.push({
      topicId: newStatus.topicId,
      someInfo : newStatus.someInfo,
      otherInfo: newStatus.otherInfo
    }) 
    

    最后,简单地这样说

    $set: { statusArray: newStatusArray}