首页 > 解决方案 > 这两个猫鼬模式表示有什么区别?

问题描述

我试图找出呈现猫鼬模式的两种情况之间的区别。我正在寻找一个帖子,用户可以在该帖子下发表评论。在一种情况下,我将 Comment 模式与(主)Post 模式放在同一个文件中,如下所示,在情况 1 中,而另一种情况涉及为各自的(Comment 和 Post)模式提供单独的文件,如在情况 2 中所示. Comment 模式在 Post 模式中被适当地引用。

最初,我使用第一种方法/案例创建并保存了一个帖子(然后添加了一些虚拟评论)。之后,在分离这两个模式之后,我无法在数据库中添加/获取评论。那么,什么给了?我对此没有最丰富的知识,因此非常感谢您的解释。

我希望我在描述我的困境时足够简洁。

以下是相关的代码片段。

案例 1:同一文件中的评论和发布模式

import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  body: { type: String },
  addedBy: { type: Schema.Types.ObjectId, ref: 'User' },
});

const PostSchema = new Schema({
  //...
  comments: [CommentSchema],
  //...
  },
  { 
    timestamps: true,
  },
);

const Post = mongoose.model('Post', PostSchema);

export default Post;

案例 2:在单独的文件中评论和发布模式

//comment.js
import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  body: { type: String },
  addedBy: { type: Schema.Types.ObjectId, ref: 'User' },
});

const Comment = mongoose.model('Comment', CommentSchema);

export default Comment;

/******************************************************/

//post.js

import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const PostSchema = new Schema({
  //...
  comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
  //...
  },
  { 
    timestamps: true,
  },
);

const Post = mongoose.model('Post', PostSchema);

export default Post;

标签: javascriptnode.jsmongodbmongoose

解决方案


推荐阅读