【发布时间】:2020-12-22 12:13:18
【问题描述】:
我知道有很多类似的问题,但它们太老了,因为 Mongodb 在过去 5-6 年里已经发展了很多,我正在寻找一个好的模式设计。
目标:我希望有一个用户与 cmets 的帖子。
到目前为止我的设计是:
- 单独的post模型:
const projectSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
title: { type: String, required: true },
image: { type: String, default: undefined },
description: { type: String, required: true, minLength: 200, maxlength: 500 },
comments: [{
type: mongoose.Schema.Types.ObjectId, ref: 'Comment'
}],
state: { type: Boolean, default: true },
collaborators: { type: Array, default: [] },
likes: { type: Array, default: [] }
})
- 还有一个单独的 cmets 模型:
const commentSchema = new mongoose.Schema({
comment: { type: String, required: true },
project: { type: String, required: true, ref: 'Project' },
user: { type: String, required: true, ref: 'User' }
})
我选择关系方法的原因是,如果 cmets 的数量增加到 10,000 个,它将大大增加模式的大小。
这样,无论我们可以使用它们的 ID 填充多少个 cmets,我们自己也会有不同的 cmets 集合。
参考:one-to-many
这对我的项目来说是个好方法吗?
我从一篇文章中查询 cmets 的方式:
const project = await Project.findById(
new mongoose.Types.ObjectId(req.params.projectId)
).populate({
path: 'comments',
populate: { path: 'user' }
}).lean()
【问题讨论】:
标签: node.js mongodb express mongoose mongoose-schema