繁体   English   中英

使用mongodb嵌入集合

[英]Embed the collections using mongodb

我只是开始使用mongodb和nodejs。 我知道mongodb不支持joins.I只是将数据插入mongodb中,我的文档看起来像:

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

现在,用户对此帖子发表评论。 应该是这样的:

{
   "_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", 
}

这是我的模特,

   //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: ''}

    });

我的问题是我不知道我使用哪种方式使用nodejs插入评论数据,并且我的文档将被嵌入。 这是我的代码:

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});
});

请帮忙

卡兰,

假设您具有以下架构:

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);

您可以将嵌入文档添加到数组中,如下所示:

// 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