sahil
sahil

Reputation: 193

Nestjs- Got 'undefined' as output while fetching data from mongodb in json format

I am trying to fetch name and price property of a collection from MongoDB and I got output like this.

enter image description here

When I fetched name property then it shows correct value, but when I fetched price property then I got undefined value.

Note: i don't want to fetch all the properties which available on total. i just want to fetch price property of an object which is on first index of an array

Here is the code of service-:

async total(){
    const total= await this.usersmodel.find().exec()
    try{
        //return total[0].name
        console.log(total[0].name)
        console.log(total[0].price)
    }
    catch(error){
        return error.message
    }
}

Here is the code of controller-:

@Post('total')
async total(){
    return this.usersService.total();
}
}

Upvotes: 0

Views: 1298

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26370

You're not returning any data from the service. You need to return what you fetched from Mongo.

async total(){
    const total= await this.usersmodel.find().exec()
    return total;
}

or

async total(){
    return await this.usersmodel.find().exec()
}

If you want to select only one field like price, use .select("price"). Or .select("name price") if you want more than one.

Also add .lean() to get raw data and not some Mongoose weirdo. Currently you're not getting JSON, but an array of Mongoose weirdos. By weirdo I mean stupid Mongoose objects, often immutable, with hidden keys and methods, that look like simple JSON but are absolutely not. .lean() will give you simple JSON. And it's faster.

usersmodel.find().select("price").lean().exec()

Upvotes: 1

Related Questions