【发布时间】:2020-07-28 15:16:42
【问题描述】:
我正在使用 MERN 创建社交网络应用。到目前为止,我所做的一件事是用户可以创建帖子,我也有追随者和追随者。我的新任务是在帖子上做出选择,使其可以是公开的或私密的。我不知道该怎么做。有没有人想法或代码示例如何做到这一点?谢谢!
这是我的帖子模型:
const PostSchema = new Schema({
userID: {
type: Schema.Types.ObjectId,
ref: 'user'
},
content: {
type: String,
required: true
},
registration_date: {
type: Date,
default: Date.now
},
likes: [
{
type: Schema.Types.ObjectId,
ref: "user"
}
],
comments: [
{
text: String,
userID: {
type: Schema.Types.ObjectId,
ref: 'user'
}
}
]
})
这是我的用户模型:
const UserSchema = new Schema({
first_name: {
type: String,
required: true
},
last_name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
registration_date: {
type: Date,
default: Date.now
},
profile_image: {
type: String,
default: ''
},
user_bio: {
type: String,
required: false
},
followers: [{
type: Schema.Types.ObjectId,
ref: "user"
}],
following: [{
type: Schema.Types.ObjectId,
ref: "user"
}]
})
这里是创建帖子的逻辑:
router.post('/', auth, (req, res) => {
const newPost = new Post({
userID: req.user._id,
content: req.body.content
})
newPost
.save()
.then(post => {
res.json(post)
})
.catch(err => console.log(err))
})
在前端,我制作了带有“公共”和“私人”选项的下拉菜单
编辑 这是我获得所有帖子的路线:
router.get('/', auth, (req, res) => {
Post
.find()
.populate('userID', 'first_name last_name profile_image _id')
.sort({ registration_date: -1 })
.then(post => res.json(post))
.catch(err => res.json(err))
})
【问题讨论】:
标签: node.js reactjs mongodb mern