【问题标题】:Add item to multidimentional object array in Mongoose将项目添加到 Mongoose 中的多维对象数组
【发布时间】:2020-01-12 12:13:27
【问题描述】:

我有这样的 Mongoose 用户模式,但我想将数组中的项目推送到我的对象之一中

这是架构示例

const userSchema = new Schema({

  tokens:[{
    token: {
        type: String,
        requird: true
    }
  }],
  tradings: {
    buy: {
        data: {
            type: Array
        }
    },
    sell: {
        data: {
            type: Array
        }
    },
    total: {
        data: {
            type: Array
        }
    }
  }
})

我想插入一个对象const obj = { trade: 234234, time: 345345 } 将数据放入购买中,因此插入后应如下所示:

"tradings": {
   "buy": {
      "data": [{ trade: 234234, time: 345345 }]
   },
   "sell": {
      "data": []
   },
   "total": {
      "data": []
   }
}

我正在使用一个函数来做,如下

Users.findOneAndUpdate(
    { _id : req.body.id },
    {
        tradings : {
            $push: {
                buy : req.body.obj
            }
        }
    },
    {
        new: true
    },
    function(error, doc){
        if(error){
            res.status(500).json({
                error: error
            })
        }else{
            res.status(201).json({
                message: req.body.data.id
            })
        }
    }
)

但是没有任何东西插入到数组中

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    您的tradings 字段具有以下结构:

    tradings: {
      buy: {
        data: {
            type: Array
        }
      },
      ...
    }
    

    并且您想在data 中推送项目,而不是buy。而且,$push 具有以下形式:

    { $push: { <field1>: <value1>, ... } }
    

    所以你的更新应该是:

    Users.findOneAndUpdate(
    { _id : req.body.id },
    {
        $push: {"tradings.buy.data": req.body.obj}
    },...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多