我有一个用户对象,其中包含几个数组,看起来像这样:
{_id: "5b90a261ff3712000495ca29",
name: "Udit",
email: "guru.udit@bmail.com",
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}
答案 0 :(得分: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}
}
})