Akshath Kumar Akshath Kumar - 15 days ago 7
Node.js Question

Getting unspecified data while fetching data using mongoose find query

Here is my code

fetchAll(){
return new Promise((resolve, reject) => {
User.find({})
.exec((err: any, res: any) => {
if(err){
reject(new Error("No heroes found"));
}else{
resolve(res);
console.log(res);
}
})
});
}


I am calling above method from controller using,

getUsers():Promise<IUser[]> {
return this.userService.fetchAll().then((users) => {
return users;
}).catch((err) => {
debug(`ERROR:${module}:getHeroById`)(err);
throw new NotFoundError(err.message);
});
}


While accessing api end point i am getting below result which contain some unwanted data.

enter image description here

Answer

In order to only render the dataValues of your instance, you can use toJSON() method of mongoose.

Your retrieve query should look like :

fetchAll(){
    return new Promise((resolve, reject) => {
        User.find({})
        .exec((err: any, res: any) => {
            if(err){
                reject(new Error("No heroes found"));
            }else{
                users = res.map( user => user.toJSON() );
                resolve(users);
                console.log(users);
            }
        })
    });
}