node.js - 具有其他模式数组字段的猫鼬模式
问题描述
首先,我是一个初学者,目前,我正在研究社交媒体博客类型。现在,我有我的userSchema和postSchema模型:
用户模型
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please insert your name'],
},
email: {
type: String,
required: [true, 'Please insert your email'],
unique: true,
lowercase: true, //transform into lowercase / not validator
validate: [validator.isEmail, 'Please provide a valid email'],
},
avatar: {
type: String,
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user',
},
password: {
type: String,
required: [true, 'Please provide a password'],
minLength: 8,
select: false,
},
passwordConfirm: {
type: String,
required: [true, 'Please confirm your password'],
validate: {
validator: function (el) {
return el === this.password;
},
message: 'Passwords are not the same',
},
},
passwordChangedAt: Date,
posts: [] // ???????????????
});
后模型
const postSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'A post must have a title'],
},
author: {
type: String,
required: [true, 'A post must have a title'],
},
likes: {
type: Number,
default: 10,
},
comments: {
type: [String],
},
image: {
type: String,
},
postBody: {
type: String,
required: [true, 'A post must contain a body'],
},
createdAt: {
type: Date,
default: Date.now(),
select: false,
},
});
现在我不知道这是否是最好的方法,但我正在考虑在userSchema中有一个类型为postSchema数组的字段,这样我将为每个用户创建他们自己的帖子。我可以这样做吗?如果不是我怎么能做到这一点?我应该使用搜索参数字段来过滤作者的帖子吗?我真的很困惑我应该如何处理这种情况。感谢你们
解决方案
看看这个例子
const UserSchema = new mongoose.Schema({
username: String,
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}]
})
const PostSchema = new mongoose.Schema({
content: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
})
const Post = mongoose.model('Post', PostSchema, 'posts');
const User = mongoose.model('User', UserSchema, 'users');
module.exports = { User, Post };
信用:https ://medium.com/@nicknauert/mongooses-model-populate-b844ae6d1ee7
推荐阅读
- python - 如何始终在交互式 matplotlib 窗口中包含完整的图例/额外的艺术家
- automated-tests - cypress 中的工具提示测试
- html - 使用大型自定义拇指图像扩展输入范围的移动
- php - 按性别和年龄对多维数组进行排序
- php - 如何检查多个日期范围之间的重叠日期?
- windows - Docker 拉未经授权:需要身份验证
- c# - .NET Core 与 .NET Framework,我的代码作为 .NET Core 的一部分工作,但不作为 .NET 框架的一部分,为什么?
- scikit-learn - 如何将一组数字分成两个簇并返回对应索引的两个子集?
- .net-core - .NET Core 默认依赖注入与 Castle DynamicProxy
- python - 语法错误。无法通过输入语句