我想通过登录用户在我的user / myarticlesview中仅显示文章。 我怎样才能做到这一点: 这是我的用户模型和文章架构:
let userSchema = mongoose.Schema(
{
email: {type: String, required: true, unique: true},
passwordHash: {type: String, required: true},
salt: {type: String, required: true},
articles: [{type: ObjectId, ref: 'Article'}],
roles: [{type: ObjectId, ref: 'Role'}]
}
);
let articleSchema = mongoose.Schema (
{
author: {type: ObjectId, ref: 'User'},
title: {type: String, required: true },
content: {type: String, required: true },
phone: {type: Number, required: true },
date: {type: Date, default: Date.now() }
}
);
我想在我的userController中执行此操作并将其传递给视图:
myArticlesGet: (req, res) => {
if (!req.isAuthenticated()) {
res.redirect('/');
return;
}
res.render('user/myarticles')
}
我无法弄清楚如何进行查询。谢谢。
答案 0 :(得分:1)
当您使用express sessions
时,您可以在用户通过身份验证后将userId
存储在快速会话中,然后您就可以从用户那里获取用户文章
User.find({_id: req.session.userId}).populate('articles')