【发布时间】:2020-11-15 13:36:38
【问题描述】:
所以,我有一个(猫鼬)帖子模型和评论模型,我想在不存储整个子文档的情况下链接这两者,我的要求是在帖子中存在对子评论的引用数组和一个评论以具有对其父帖子的单一引用。 编辑:是否可以自动设置参考?
【问题讨论】:
标签: javascript node.js database mongodb mongoose
所以,我有一个(猫鼬)帖子模型和评论模型,我想在不存储整个子文档的情况下链接这两者,我的要求是在帖子中存在对子评论的引用数组和一个评论以具有对其父帖子的单一引用。 编辑:是否可以自动设置参考?
【问题讨论】:
标签: javascript node.js database mongodb mongoose
您必须使用mongoose.Schema.Types.ObjectId 类型才能引用另一个集合。它的作用类似于 SQL 语言中的 foreignKey。
但你第二个问题的答案是否定的。你必须手动设置。
顺便说一句,更好的设计是将您的引用或 foreignKey 存储在两个集合之一中,而不是两个集合中。
在数据库语言中,如果您有one-to-many 关系,就像这里您的帖子有很多 cmets,更好的方法是将 postId(作为 foreignKey)存储在评论集合中。当您想要查找特定帖子的所有 cmets 时,您可以查询您的 cmets 集合并仅查找具有您特定 postId 的记录。
这是评论模式:
let commentSchema = new mongoose.Schema({
text: String,
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
});
这是帖子架构
let postSchema = new mongoose.Schema({
text: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
default: []
}]
});
这里是创建帖子和 cmets 的代码:
const createPost = async () => {
let post = new PostModel({
text: 'Here is a sample post',
});
await post.save();
}
const createCommentOnPost = async (postId) => {
let comment = new Comment({
text: 'Sample comment',
post: postId
});
await comment.save();
await Post.updateOne({_id: postId}, {$push: {comments: comment}});
}
【讨论】: