SakoBu SakoBu - 17 days ago 6
Node.js Question

Getting all posts that belong to one user in Node / Express

I have 2 models User & Revive as you can see below... in the router(see below) what is the query to get all revives that belong to the user/creator to display on his dashboard/profile page?

User Model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});

module.exports = mongoose.model('User', userSchema);


Revive Model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var reviveSchema = new Schema({
reviveTitle: {
type: String,
required: true
},
reviveStory: {
type: String
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
}
});

module.exports = mongoose.model('Revive', reviveSchema);


Router:

router.get('/dashboard', isLoggedIn, function(req, res) {
code ?? to get all revives that belong to the creator/user only ??
res.render('users/dashboard', {currentUser: req.user});
});

Answer

Well, I would setup the Revive schema bit differently:

author: { type: mongoose.Schema.Types.ObjectId, ref: "User"}

Then you should be able to just do a proper find:

const Revive = mongoose.model('Revive');

router.get('/dashboard', isLoggedIn, function(req, res) {
    Revive.find({author:req.user._id}, (e, revives) => {
       // however you handle errors goes first
       res.render('users/dashboard', {currentUser: req.user, revives: revives});
    });
});