使用mongodb嵌入Json数据

时间:2015-11-19 12:20:32

标签: javascript json angularjs node.js mongodb

我正在使用mongodb和nodejs。我刚开始使用mongodb。我有一个查询。这是我的mongdb文档:

{
   "_id": ObjectId("564dacf84d52785c1d8b4567"),
    "content": "This blog created by karanSofat",
   "html": "<p>This blog created by karanSofat</p>\n",
   "saved_at": ISODate("2015-11-19T11:05:28.618Z"),
   "title": "my blog" 
}

我想与这些数据建立联系。我希望我的json在用户评论时应该喜欢。

{
   "_id": ObjectId("564dacf84d52785c1d8b4567"),
   "comments": [
     {
       "name": "arpit",
       "email": "arpit@gmail.com",
       "comment": "How can Make we this at good",
       "posted_at": ISODate("2015-11-19T11:06:03.628Z") 
    },
     {
       "name": "sumit",
       "email": "sumit@ggi.net",
       "comment": "this is also well for me",
       "posted_at": ISODate("2015-11-19T11:06:27.172Z") 
    } 
  ],
   "content"▼: "This blog created by karanSofat",
   "html": "<p>This blog created by karanSofat</p>\n",
   "saved_at": ISODate("2015-11-19T11:05:28.618Z"),
   "title": "my blog" 
}

我正在使用角度js和节点js.Here是我的代码:

app.post('/comments/:id', function(req, res) {
var id = req.params.id;
var comments = JSON.parse(JSON.stringify(req.body));



res.json({data:id,data2:input});
});

1 个答案:

答案 0 :(得分:0)

使用结构创建一个名为comment的新mongoose模型:

{
    name: {
        type: String
    },
    email: {
        type: String
    },
    comment: {
        type: String
    },
    posted_at: {
        type: Date
    }
}

每个文档都会被赋予它自己独特的_id。保存每个注释时,请更新blog_post文档上的注释数组。然后你就可以利用Mongoose的内置人员来填充#39;功能性:

http://mongoosejs.com/docs/populate.html