node.js - 如何仅获取给定用户 Express.js 的文章

标签 node.js mongodb express mongoose

我想在我的用户/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 中执行此操作并将其传递给 View :

myArticlesGet: (req, res) => {
    if (!req.isAuthenticated()) {
        res.redirect('/');
        return;
    }

    res.render('user/myarticles')

}

我不知道如何进行查询。谢谢。

最佳答案

当您使用express session时,您可以在用户经过身份验证时将userId存储在express session中,然后您可以像这样从用户那里获取用户文章

User.find({_id: req.session.userId}).populate('articles')

关于node.js - 如何仅获取给定用户 Express.js 的文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43226245/

相关文章:

file-upload - 如何从 node.js 上传文件

node.js - 如何查询MongoDb中的所有项目

mongodb - 执行从副本集重新启动到独立时的异常

node.js - react : rendering content (view) according to requested route (ExpressJS)

node.js - Angular.js 可以在脚本标签中的 Jade 模板中进行插值吗?

node.js - express.js,为什么 res.write 不在 api 引用中

node.js - 使用 fast-csv 将 [object Object] 写入 csv 文件

javascript - 在nodejs中迭代项目数组

node.js - 如何允许 CORS 用于无服务器中的自定义 header ?

mongodb - 如何用MongoDB(Motor)实现FastAPI的pytest