0

In my database I have Models which are filled like this:

{ name: 'Name',
  surname: 'Surname',
  address: 'address',
  email: 'email@mail.com',
  addedNumbers: 
   [ { phone: 'Mobile',
       number: 123,
       default: false,
       _id: 5a93e11a4f7bc709691d81d6 },
     { phone: 'Telephone',
       number: 321,
       default: true,
       _id: 5a93e11a4f7bc709691d81d7 },
     { phone: 'Fax',
       number: 456,
       default: false,
       _id: 5a93e11a4f7bc709691d81d8 } ],
  _id: 5a93e11a4f7bc709691d81d5,
  __v: 1 }

I was wondering how to return an object inside the addedNumbers array whose default key is equal to true. And to pass that object to my HTML file

I have tried something like this but it's not working :

 Contact.find({}, function(err, foundContact){
        if(err) {
            console.log(err);
        } else {
            Contact.find({"addedNumbers.default": true}, function(err, defaultnum){
                if(err){
                    console.log(err);
                } else {
                    res.render("index", {contacts: foundContact, number: defaultnum});
                    // console.log(defaultnum);
                }
            });
        }
    });
jops
  • 17
  • 3

1 Answers1

0

try this

Contact.aggregate([{
$unwind: "$addedNumbers"},
  {
    $match: {
      "addedNumbers.default": true
    }
  },
  {
    $group: {
      _id: '$_id',
      addedNumbers: {
        $push: "$addedNumbers"
      },
      name: {
        $first: '$name'
      },
      email: {
        $first: '$email'
      },
      address: {
        $first: '$address'
      }
    }
  }
],callback)
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
  • [ { addedNumbers: [ [Object], [Object], [Object] ], _id: 5a93ec11d0aea50b8e1c80f9, name: 'asd', surname: 'asd', address: '', email: '', __v: 1 } ] This is the output, I need only the object with default=true inside the addedNumbers array – jops Feb 26 '18 at 11:36
  • I have updated my answer plz check – Rahul Sharma Feb 26 '18 at 12:20