Node.js 文章的Mongoose模式

Node.js 文章的Mongoose模式,node.js,mongodb,mongoose,pug,mongoose-schema,Node.js,Mongodb,Mongoose,Pug,Mongoose Schema,我正在建立一个新闻网站,我希望这个猫鼬模式: let mongoose = require('mongoose'); let articleSchema = mongoose.Schema({ image1:{ type: String, required: true }, title:{ type: String, required: true }, author:{ type: String, required: true

我正在建立一个新闻网站,我希望这个猫鼬模式:

let mongoose = require('mongoose');

let articleSchema = mongoose.Schema({
  image1:{
    type: String,
    required: true
  },
  title:{
    type: String,
    required: true
  },
  author:{
    type: String,
    required: true
  },
  date:{
    type: String,
    required: true
  },
  updated:{
    type: String,
    default: 'not updated'
  },
  title_nd:{
    type: String,
    required: false
  },
  body:{
    type: String,
    required: true
  },
  comments: [commentsSchema],
  likes:{ type:Number, default:0 }
});

let Article = module.exports = mongoose.model('Article', articleSchema);

我想添加一个表单,以便用户可以添加他们的评论。
问题是我如何为注释创建一个新的模式并将其链接到文章模式,然后如果用户添加注释,该注释将添加到数据库中,然后显示在文章注释部分?

在我看来,为注释创建一个单独的模式不是一个好主意,因为它是
一对几映射的经典案例
,是嵌入文档的理想用例。为了给你一个关于数据建模的基本概念,我在这里引用

你需要考虑两个因素:

  • 一对N中“N”端的实体是否需要独立
  • 关系的基本原则是什么:是一对几;一对多;还是一个到水柱
基于这些因素,您可以从三种基本的一对N模式设计中选择一种:

  • 如果基数是一对几,并且不需要访问父对象上下文之外的嵌入对象,则嵌入N侧
  • 如果基数为一对多,或者如果N侧对象因任何原因应独立,则使用N侧对象的引用数组
  • 如果基数为1到squillions,则使用对N侧对象中一侧的引用
请参考mongodb博客上一篇非常好的文章


即使在这之后,如果您认为链接到另一个模式是一个好主意,请参考此SO问题-

因此我找到了解决方案:

/:id是具有所有id的所有文章
路由器.post('/:id',函数(req,res){
让评论={};
comment.body=req.body.body;
comment.user=req.user;
comment.date=新日期(date.now()).toDateString();
//快速验证器
要求检查主体(“主体”).len(5100);
让错误=[];
errors=req.validationErrors();
如果(错误){
Article.findById(req.params.id,函数(err,Article){
如果(错误)抛出错误;
闪光要求(“危险”,“车身最小长度为5,最大长度为100”);
res.redirect('/articles/'+article.id);
});
}否则{
Article.findById(req.params.id,函数(err,Article){
如果(错误)抛出错误;
article.comments.push({'body':comment.body,'user':comment.user,'date':comment.date});
article.save(功能(err){
如果(错误){
犯错误;
}否则{
请求flash('success','Comment added!');
res.redirect('/articles/'+article.id);
}
});
});
}
});
编辑:以上代码的可读性更强:

router.post('/:id',异步(req,res)=>{
let article=等待article.findById(req.params.id);
如果(!条)物状态(“403”);
let articleUrl=“/articles/${article.id}”;
让评论={
body:req.body.body,
用户:req.user,
日期:新日期(date.now()).toDateString();
};

如果(commment.body.lengh>=100 | | | comment.body.length到目前为止,您的
commentschema
有什么内容吗?您可以创建注释架构,方法与创建文章架构相同,只是具有不同的属性和明显不同的模型名称。在注释架构中,您可以向注释架构添加属性创建一个可以与文章关联的
ObjectId