您好我是nodejs和mongodb的新手,我有以下結構的json文件, 我已經定義了一個貨件模式,其中「comments」部分作爲嵌套架構嵌套/嵌入模式的多個記錄沒有插入到mongodb中,nodejs
{
"buyerId": "B58",
"sellerId": "SL8",
"comments": {
"title": "title5",
"body": "body5",
"date": "12-07-2017"
}
}
我已經定義一個函數像下面
exports.post = function(req, res) {
const comments = []
var s = new shipment();
s.sellerId = req.body.sellerId;
s.buyerId = req.body.buyerId;
s.poId = req.body.poId;
s.comments.push({
title: req.body.comments.title,
body: req.body.comments.body,
date: req.body.comments.date
});
s.save(function(err) {
if (err) {
res.send(err);
}
console.log("added");
res.send({
message: 'shipment Created !'
})
})
}
以上「後」功能將正常工作時,我只有一個「意見」一節,我指的是數據得到妥善 插入mongodb如下圖所示
{
"_id": ObjectId("59689bc59058dbc812000002"),
"buyerId": "B58",
"sellerId": "SL8",
"comments": [{
"title": "title5",
"body": "body5",
"date": ISODate("2017-12-06T18:30:00Z"),
"_id": ObjectId("59689bc59058dbc812000003")
}],
"__v": 0
}
,但是當我有多個「意見」部分,如下圖所示,
{
"buyerId": "B58",
"sellerId": "SL8",
"comments": [{
"title": "title5",
"body": "body5",
"date": "12-07-2017"
},
{
"title": "title8",
"body": "body7",
"date": "12-07-2017"
}
]
}
則沒有註釋部分被插入到MongoDB的,如下圖所示。
{
"_id": ObjectId("5968c04d4c02336800000002"),
"buyerId": "B57",
"sellerId": "SL7",
"comments": [{
"_id": ObjectId("5968c04d4c02336800000003")
}],
"__v": 0
}
我應該在功能上做什麼樣的變化得到被插入到MongoDB的所有正確的註釋部分?
顯示您的實際模式,因爲它似乎實際上是「引用」而不是「嵌入」,因爲您指出問題的開始。你還應該研究這些術語,並理解它們之間的區別和意義。第二個例子實際上代表了在POST請求中發送的數據嗎?因爲在這裏請注意,第一個內容不是數組,因此可以使用'.push()',因爲它是一個單獨的元素。第二種形式是「數組」,當然,如果不迭代元素,你就不能'.push()'。 –
但在其他所有情況下,您確實需要閱讀核心文檔中的['$ push'](https://docs.mongodb.com/manual/reference/operator/update/push/)運算符。這遠遠優於你現在正在做的事情。 –