0

I am trying to loop through something but first I need to do a mongo query to get the data for the loop my query is this:

AP.find({}, function(err, allAP) {
        var ID = req.user.id;
        if(err){
          console.log(err);
        } else {
          res.locals.aps= allAP; // Set the data in locals
          next();
        }
      });

I know I need to add something in the {} part on line 1. How do I take req.user.id and then only find documents with the author.id (see below)

author: {
      id: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User"
      },
      email: String
   }

Example document currently returned:

{ _id: 59e517230a892a26cb1b7635,
    manufacturer: 'other',
    model: 'Test Model',
    bands: '2.4',
    channel: 11,
    notes: 'I am a test note for the first access point',
    __v: 0,
    author: { id: 59d7f98a77fcc221d6e3c93d, email: 'joe@example.com' } },
  • `AP.find({ 'author.id': req.user.id }, function (err, allAP) {` – Mikey Oct 19 '17 at 17:04
  • @Mikey Thank you so much it worked, I knew it had to be close to that. I tried without the quotes, but it failed didn't know quotes worked in mongo query (yeah I'm new haha) –  Oct 19 '17 at 18:23

1 Answers1

1

You can do

AP.find({"author.id":req.user.id}, function(err, allAP) {
    if(err){
      console.log(err);
    } else {
      res.locals.aps= allAP; // Set the data in locals
      next();
    }
  });
Ayush Mittal
  • 539
  • 2
  • 5
  • Thank you so much it worked, I knew it had to be close to that. I tried without the quotes, but it failed didn't know quotes worked in mongo query (yeah I'm new haha) –  Oct 19 '17 at 18:24
  • @JoshKirby The first argument of `find()` is a JavaScript object. Sometimes, like in this situation, a key of an object [needs to have quotes](https://stackoverflow.com/questions/12991969/js-object-keys-with-or-without-quotes). – Mikey Oct 19 '17 at 19:03