javascript - 这两个猫鼬模式表示有什么区别?
问题描述
我试图找出呈现猫鼬模式的两种情况之间的区别。我正在寻找一个帖子,用户可以在该帖子下发表评论。在一种情况下,我将 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;
解决方案
推荐阅读
- php - 我如何在我从数据库中获取的 get_file_contents 中使用 if else 条件
- google-cloud-platform - 为什么我无法通过 Google Cloud Platform 上的 Chrome RDP 连接到我的 Windows 虚拟机?
- python - DRF 将数据从 API 反序列化到 django 模型
- .net - Web API.Net 响应类型和序列化
- javascript - 带有 'as' 属性的通用 React TypeScript 组件(能够渲染任何有效的 dom 节点)
- mongodb - find({}) doesn't return correct result
- python-3.x - how to check an array for inputs that are outside a condition more then once
- python - 在 Pytorch 中将 L1 损失稍微调整为加权 L1 损失,梯度计算仍然可以正常工作吗?
- postgresql - How to disable subscription automatically on connexion lost (PostgreSQL Logical Replication)?
- c# - 相当于修改 EFCore 迁移