gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:59:20 25 4
gpt4 key购买 nike

我有一个用户对象,其中包含几个数组,如下所示:

{
_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
}

最佳答案

你可以这样做:

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}
}
})

关于node.js - 无法将数据推送/更新到现有的 mongo 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52201818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com