Srikar Reddy Karemma
Srikar Reddy Karemma

Reputation: 163

Get the _id of the sub-document from mongoose findOne query

The schema of my Sample model is:-

var nameSchema = new mongoose.Schema({
  firstname:String,
  lastname:String
})

var sampleSchema= new mongoose.Schema({
    number: {
      type: String
    },
    name :{
      type : [nameSchema]
    }
  });

I am trying to update the first and last name by searching them by their number property by making use of Sample.findOne({number:number}). And i am performing the update operation in the following manner:-

module.exports.updateNumber = function(req, res){
  var number= req.body.number;
  var lname= req.body.lname;
  var fname= req.body.fname;
  Sample
   .findOne({number:number})
   .select('name')
   .exec(function(err, doc){
     console.log(doc)

    var this_id;

    var  thisService = doc.name.id('this_id');
       thisService.firstname=fname;
       thisService.lastname=lname;

       doc.save(function(err, update) {
         if (err) {
           res
             .status(500)
             .json(err);
         } else {
           res
             res.render('done')
         }
       });
     })


}

If i console log the output i got is:

{ _id: 5bc5d71f47ff14361c0639d1,
  name:
   [ { _id: 5bc5d71f47ff14361c0639d2,
       firstname: 'firstname',
       lastname: 'lastname' } ] }

Is there any way, i could store _id: 5bc5d71f47ff14361c0639d2 in 'this_id' variable, so that this updation would be possible

Upvotes: 1

Views: 43

Answers (1)

scales
scales

Reputation: 127

name is an array, so if you want the first _id then name[0]._id would suffice, if you want an array of all values for _id in name, then name.map((person) => person._id) would give you an array of _id

However, more details about the context of this object would help give a better answer.

Upvotes: 1

Related Questions