简体   繁体   English

使用mongodb嵌入集合

[英]Embed the collections using mongodb

I am just start using mongodb and nodejs. 我只是开始使用mongodb和nodejs。 I know that mongodb does not supports joins.I simply insert the data in mongodb and my documents looks: 我知道mongodb不支持joins.I只是将数据插入mongodb中,我的文档看起来像:

{
   "_id": ObjectId("564dacf84d52785c1d8b4567"),
    "content": "This blog created by karanSofat",
   "html": "<p>This blog created by karanSofat</p>\n",
} 

Now user comments on this post. 现在,用户对此帖子发表评论。 it should be like this: 应该是这样的:

{
   "_id": ObjectId("564dacf84d52785c1d8b4567"),
   "comments": [
     {
       "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", 
}

Here is my models, 这是我的模特,

   //post model
// grab the mongoose module
var mongoose = require('mongoose');

// define our nerd model
// module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('post', {
    content : {type : String, default: ''},
    html : {type : String, default: ''}


});
//comment model
 var mongoose = require('mongoos
      module.exports = mongoose.model('comment', {
        name : {type : String, default: ''},
        email : {type : String, default: ''},
        comment : {type : String, default: ''},
        posted_at : {type : date, default: ''}

    });

My Problem is that I don't know on which way I insert comments data using nodejs and my document will embed. 我的问题是我不知道我使用哪种方式使用nodejs插入评论数据,并且我的文档将被嵌入。 Here is my code: 这是我的代码:

app.post('/comments/:id', function(req, res) {
var Comment = require("../app/models/comments");//comment Model
var blog = require("../app/models/blog");//blog model

var id = req.params.id; //postId
var comments = JSON.parse(JSON.stringify(req.body)); //commentdata

//code Should be here

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

Please help 请帮忙

Karan, 卡兰,

Let's assume you have the following schema: 假设您具有以下架构:

var Comments = new Schema({
    name: String,
    email: String,
    comment: String,
  , posted_at: Date
});

var BlogPost = new Schema({
  content     : String,
  html      : String,
  comments  : [Comments],
});

mongoose.model('BlogPost', BlogPost);

You can add an embed document to an array as such: 您可以将嵌入文档添加到数组中,如下所示:

// retrieve my model
var BlogPost = mongoose.model('BlogPost');

// create a blog post
var post = new BlogPost();

// create a comment
post.comments.push({
   "name": "sumit",
   "email": "sumit@ggi.net",
   "comment": "this is also well for me",
   "posted_at": ISODate("2015-11-19T11:06:27.172Z") 
});

post.save(function (err) {
  if (!err) console.log('Success!');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM