0

want this to render the currentusers user.object

app.get("/profile", isLoggedIn, (req,res)=>{
User.find({}, (err,User)=>{
    if(err){
        console.log(err);
        res.redirect("/login");
    }else{
        res.render("pages/userprofile", {User:User});
        console.log(User);
    }
})
});

this is my user schema

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const UserSchema = new mongoose.Schema({
username: String,
password: String,
review: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Review"
}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

when i run the code going to the profile route, it brings back all the users and I have tried multiple ways to only bring back one but I keep getting error

3 Answers3

0

You just have to use findOne for getting one user.

app.get("/profile", isLoggedIn, (req,res)=>{
    User.findOne({}, (err,User)=>{
        if(err){
            console.log(err);
            res.redirect("/login");
        }else{
            res.render("pages/userprofile", {User:User});
            console.log(User);
        }
    })
    });
Muslem Omar
  • 1,021
  • 12
  • 12
  • I've tried that but its not grabbing the current user in session I have figured out how to grab the current user using. User.find({_id: req.user}.... but for some reason in my ejs file when I do <%= User.username%> username comes back undefined which is odd because i have another mongoose schema that is nearly identical and it can pull username no problem – Walter Vannoy Oct 19 '20 at 16:29
  • im wondering if I can't access it because it has passport plugin.. for now im going to go make a new profile schema and see if I can use User as a reference and be able to grab the username that way will post updates – Walter Vannoy Oct 19 '20 at 16:35
0
app.get("/profile", isLoggedIn, (req,res)=>{
User.findOne({_id: req.user}, (err,User)=>{
    if(err){
        console.log(err);
        res.redirect("/login");
    }else{
        
        res.render("pages/userprofile", {User:User});
        console.log(User);
    }
})
});

I tried the findOne({...}... and it worked!!!! thank you for the help

0

You may consider using findById(id) since the Mongoose documentation suggested to use it than findOne({ _id: id }).

app.get("/profile", isLoggedIn, (req, res) => {
  User.findById(req.user, (err, User) => {
    if (err) {
      console.log(err);
      res.redirect("/login");
    } else {

      res.render("pages/userprofile", { User: User });
      console.log(User);
    }
  })
});