Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this is my model:

const userSchema = new Schema({
username: String,
password: String,
mobileno: String,
firstname: String,
lastname: String,
role: String,

expenses:[
{
billno: Number,
createdAt: Date,
amount: Number,
description: String,

}
],
total_expense: {
type: Number
},

}, { versionKey: false });

I want to retrieve a specific child record using the id:

What I have tried is:

User.find({'expenses._id': req.params.id},
              (err, doc) => {
                    if (!err) {
                       
                         res.send(doc);
                     }
                     else {
                        console.log('Error in Retriving User: ' + JSON.stringify(err, undefined, 2));
                     }
              });



This fetch all the expense records irrespective of the id.



Sample output:
{
_id: '111',
name:'test',
expenses:[
{
"_id":222,
"Bilno": "123"
},
{
"_id":333,
"Bilno": "1235"
}
]
}

My output should be:
(If I pass my id as 222 then)

{
_id: '111',
name:'test',
expenses:[
{
"_id":222,
"Bilno": "123"
}
]
}

I need only the record to which is id is passed.

What I have tried:

<pre>User.find({'expenses._id': req.params.id},
              (err, doc) => {
                    if (!err) {
                       
                         res.send(doc);
                     }
                     else {
                        console.log('Error in Retriving User: ' + JSON.stringify(err, undefined, 2));
                     }
              });
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900