2017-07-14 64 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 }); 
}