0

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();
}
}
3
  • return await this.usersService.total();? Commented May 19, 2020 at 10:53
  • Nope, not that. What does console.log(total) show you? Commented May 19, 2020 at 10:54
  • if i use console.log(total) then i get all the objects of array, but i want to fetch only price from object which is present on 0 index of array. Commented May 19, 2020 at 11:01

1 Answer 1

1

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()

Sign up to request clarification or add additional context in comments.

1 Comment

If i used your method then i'll get all the properties of document but i want only specific property that is price and nothing else. in screenshot i just trying to tell you my issue us that if i fetch name then it works properly but when am trying to fetch price its shows undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.