Saturday, 8 April 2017

Cannot get property from the object retrieved by find query in Mongoose

I want to retrieve user data from mongodb, except userpw. so I select email propert only. When I send response as res.json(user) it prints the object well. but it fails, response shows undefined when I use user.email instead.

here is query I called:

User.findOne({username: req.params.username}, {email: 1}, (err, user) => {
       if (err) {
           console.log(err.stack);
           return;
       }
       console.log(user.email, typeof user);
       res.send(user.email);
});

Here is my userSchema:

const userSchema = new Schema({
    username: String,
    email: String,
    userpw: String
});

Here is my data on MongoDB:

> db.users.insert({username: "kkr", email: "kidkkr@naver.com", userpw: "aabb"})
WriteResult({ "nInserted" : 1 })
> db.users.find()
{ "_id" : ObjectId("58e99299d3e4e1768eb68cda"), "username" : "kkr", "email" : "kidkkr@naver.com", "userpw" : "aabb" }



via kidkkr

No comments:

Post a Comment