无法将数据推送/更新到现有的mongo对象中

问题描述 投票:1回答:1

我有一个用户对象,里面有几个数组,如下所示:

{_id: "5b90a261ff3712000495ca29", 
  name: "Udit", 
  email: "[email protected]", 
  password: "sjsndj",
  education:[],
  professionalexp:[],
  projects:[],
  skills:[]
}

我正在使用express API将数据推送到带有某些对象的教育数组中,以下是我试图更新mongo数据的代码。当我尝试推送和更新数据时,我看不到任何响应。我应该如何进行并一次推送阵列或多个阵列

app.put('/api/updatefield/',function (req, res){
      User.update({_id: req.body._id}, {
        $push :{
          "education.$.University": "something that is there"
        }
      },function (err, result) {
        if (err) {
          res.send(err)
        }
        if (result) {
          res.json(result)
        }
      })

})

也是为了参考,这是我通过API主体推送的数据,我在其余服务器上的req.body中获取

{"summary":"some summary","education":[{"name":"Institue","from":"19/07/2018","to":"30/07/2018"}],"professional":[{"name":"Company","from":"19/07/2018","to":"30/07/2018"}],"cardCount":1,"cardCount2":1}
node.js mongodb reactjs express mongoose
1个回答
2
投票

你可以这样做:

    User.update({_id: ObjectId("5b910b0acb5b7646e630cefe")}, {
    $push: {
        "education": {
            "summary": "some summary",
            "education": [{"name": "Institue", "from": "19/07/2018", "to": "30/07/2018"}],
            "professional": [{"name": "Company", "from": "19/07/2018", "to": "30/07/2018"}],
            "cardCount": 1, "cardCount2": 1
        }
    }
})

对于多个对象:

User.update({_id: ObjectId("5b910b0acb5b7646e630cefe")}, {
    $push: {
        "education": {
            $each: [{
                "summary": "some summary",
                "education": [{"name": "Institue", "from": "19/07/2018", "to": "30/07/2018"}],
                "professional": [{"name": "Company", "from": "19/07/2018", "to": "30/07/2018"}],
                "cardCount": 1, "cardCount2": 1
            }, {"a": 2}]
        }

    }
})

用于推入多个对象:

User.update({_id: ObjectId("5b910b0acb5b7646e630cefe")}, {
        $push: {
            "education": {
                $each: [{
                    "summary": "some summary",
                    "education": [{"name": "Institue", "from": "19/07/2018", "to": "30/07/2018"}],
                    "professional": [{"name": "Company", "from": "19/07/2018", "to": "30/07/2018"}],
                    "cardCount": 1, "cardCount2": 1
                }, {"a": 2}]
            },
           "professionalexp" : {"a":2}
        }
    })
© www.soinside.com 2019 - 2024. All rights reserved.