Search code examples
node.jsmongodbmongooseejsbody-parser

im trying to pull the current user's data only from my mongodb to use in ejs file for a profile route where it should be custom to each user's inputs


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


Solution

  • 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);
        }
      })
    });