0

I want to query the DB and return a set of documents where the selected nested field is equal to true. As a contrived example: Let's assume I have Facebook users, and their data is stored with this format.

const UserSchema = new Schema({
  name: String, 
  age: Number, 
  permissions: {
    allow_comments: Boolean, 
    allow_likes: Boolean,
    allow_shares: Boolean
  }
})

And I want to return all the users who have permissions.allow_likes set to true. Notice, it's not a full-on sub-document, it's just an object with some data in it (maybe that's bad, idk).

I looked around and didn't find much. So then, I tried this:

UserModel.find({permissions: {allow_likes: {$eq: true}}})
  .then(users => console.log(users));   // returns []; 

Thanks in advance!

TJBlackman
  • 1,895
  • 3
  • 20
  • 46
  • Use [dot notation](https://docs.mongodb.com/manual/tutorial/query-embedded-documents/#query-on-nested-field) for querying fields inside an embeddded document.Something like query part `{ "permissions.allow_likes":true }` – s7vr Jan 05 '18 at 23:48
  • This actually works! ha ha So simple! Although - It's worth noting the property with `dot-notation` MUST be in quotes. That's probably obvious, but I tried it both ways... Thank you! – TJBlackman Jan 06 '18 at 00:16
  • Looks like it. :| Thanks for links! They both are helpful! – TJBlackman Jan 06 '18 at 00:23

1 Answers1

0

I don't know how are you using the Schemas and Models but I don't think you are doing it right. For this case I would use a separate file to store the user schema like this (/schemas/user.js):

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
   name: String, 
   age: Number, 
   permissions: {
       allow_comments: Boolean, 
       allow_likes: Boolean,
       allow_shares: Boolean
});

module.exports= mongoose.model('User',userSchema);

After that, to use it, you can do the following:

var userModel = require('../schemas/user.js')
var mongoose = require('mongoose');

userModel.find(
   {
       permissions: {allow_likes: true}
   },(err,results) => {

      if (err) {
      //well you got an error
      }
      if (results)
      {
          console.log("Results: "+results);
      }
   }

);
the_ccalderon
  • 2,006
  • 2
  • 13
  • 24
  • 1
    You're absolutely correct about how to create and query a collection. I omitted small parts of the code to be concise and show only the issue. Unfortunately this method does not work, sadly. I tried `userModel.find({permissions:{allow_likes:true}})` and no dice. The other comment does work though. Thanks for looking! – TJBlackman Jan 06 '18 at 00:14