简体   繁体   中英

express mongoose display data on view after find

I have that code:

app.get("/users/:username", function(req,res){
var data = req.params.username;
User.find({'username' : new RegExp(data, 'i')}, function(err, foundUser){
        console.log(foundUser);
        if(err){
            console.log(err);
            res.redirect("/")
        }else{
            res.render("users/show", {us: foundUser})
        }
    })
});

The idea is to find username in database by username and pass it to the view and display it. Now when i consol log foundUser it shows the whole object in my h1 and also

 <div class="container">
    User profile
  <h1><%=us%></h1>
  </div>

When i try to access us.username it doesnt show anything and console says its undefined.

User.find will return an array of documents. Even if your query only matches a single document, it will still be an array with one value. So foundUser.username won't work. foundUser[0].username should work.

If you use User.findOne it will return a single document, not in an array. Then foundUser.username should work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM