2017-07-14 77 views
1

您好我是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的所有正確的註釋部分?

+0

顯示您的實際模式,因爲它似乎實際上是「引用」而不是「嵌入」,因爲您指出問題的開始。你還應該研究這些術語,並理解它們之間的區別和意義。第二個例子實際上代表了在POST請求中發送的數據嗎?因爲在這裏請注意,第一個內容不是數組,因此可以使用'.push()',因爲它是一個單獨的元素。第二種形式是「數組」,當然,如果不迭代元素,你就不能'.push()'。 –

+0

但在其他所有情況下,您確實需要閱讀核心文檔中的['$ push'](https://docs.mongodb.com/manual/reference/operator/update/push/)運算符。這遠遠優於你現在正在做的事情。 –

回答

0

最初的註釋是第二個示例中的數組註釋是一個數組。 你的函數

s.comments.push({ 
    title: req.body.comments.title, 
    body: req.body.comments.body, 
    date: req.body.comments.date 
}) 

如果評論是一個對象纔有效。把在for循環,使其使用數組像這樣

for(var i = 0; i < req.body.comments.length; i++){ 
    s.comments.push({ 
     title: req.body.comments[i].title, 
     body: req.body.comments[i].body, 
     date: req.body.comments[i].date 
    }) 
} 
+0

非常感謝您的提示,我對您的提示做了一些修改,並且工作正常,我更改了代碼\t(var i = 0; i

+0

哈哈我的壞,好吧我修好了 –

0

不是指定每個屬性的值,使實例,並通過身體直接進去。

const s = new shipment(req.body) 

然後當你發送數據請求,發送以下列格式

{"buyerId": "B58", "sellerId": "SL8", "comments": [{ "title": "title5", "body": "body5", "date": "12-07-2017" }, { "title": "title8", "body": "body7", "date": "12-07-2017" } ] }

0

我試圖像下面,它的工作。

for(var i = 0; i < req.body.comments.length; i++){ 
s.comments.push(
{ title: req.body.comments[i].title, 
body : req.body.comments[i].body, 
date : req.body.comments[i].date }); 
}