petko kostadinov
petko kostadinov

Reputation: 55

How to take only articles by given user Express.js

I want to display in my user/myarticlesview only articles by logged in user. How can i do that: Here is my User model and Article schema:

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() }
}

);

I want to do this in my userController and passed it to the view:

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

    res.render('user/myarticles')

}

I cant figure it out how to make the query.Thank you.

Upvotes: 1

Views: 53

Answers (1)

Anas Aboureada
Anas Aboureada

Reputation: 96

As you are using express sessions you can store userId in the express session when the user is authenticated and then you can get user articles from user like that

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

Upvotes: 1

Related Questions