This is my data collection which are in MongoDB and I want to retrieve data of the model attribute.
{"_id":{"$oid":"61dd83fce198010f26b2f47d"},"assetID":"0001","assetCategory":"Laptop","model":"Asus","serialNumber":"0x001","status":"Non-Available","__v":{"$numberInt":"0"}}
I wrote my code like the below code segment by using express js.
router.get("/detail/:id",async(req,res)=>{
let ID = req.params.id;
await Asset.find({_id:ID}).then((assets)=>{
res.json(assets)
}).catch((err)=>{
console.log(err)
})
})
After that, I was able to get a json object like this.
[
{
"_id": "61dd83fce198010f26b2f47d",
"assetID": "0001",
"assetCategory": "Laptop",
"model": "Asus",
"serialNumber": "0x001",
"status": "Non-Available",
"__v": 0
}
]
But I want to get only a data of model attribute. Can anyone please explain what are the changes that I should do? Thank you!
CodePudding user response:
Try this:
await Asset.find({_id:ID},{model:true}).then((assets)=>{
The second arg to find() is the projection, the equivalent of select model .. in SQL. You can add as many fields as you wish, e.g.
await Asset.find({_id:ID},{model:true, status:true}).then((assets)=>{
Note that _id is always automatically returned. You can inhibit this as follows:
await Asset.find({_id:ID},{model:true, _id:false}).then((assets)=>{
