0

I have a collection Events in my Mongodb and it has an array filed called for_who.

This field is for checking if a user id is in this array, so this user can see this Event. I want to get the Events that for_who field contains user_id.

This is my current query:

Events.find(
    { for_who: { "$in" : [user_id]} } 
).lean().exec(function(err , obj) { ... });

my schema:

var eventSchema = new mongoose.Schema({ 
  id                : { type: Number , required: true , unique: true } ,
  title             : { type: String , required: true } ,
  created_at        : { type: String , required: true } ,
  for_who           : { type: Array } 
});

var Events = mongoose.model('Events', eventSchema);
kamalon
  • 11
  • 4
  • This looks like a dupe of https://stackoverflow.com/questions/18148166/find-document-with-array-that-contains-a-specific-value, but what you're trying should also work, even though `$in` isn't required. What's not working about it? – JohnnyHK Dec 12 '16 at 14:15
  • No I`ve seen that but doesn`t work!! – kamalon Dec 12 '16 at 14:35
  • 1
    Can you [edit] your question to include the schema definition for `Events`, the value of `user_id`, and the document you're expecting the query to return? – JohnnyHK Dec 12 '16 at 14:37
  • I edited my question and included event schema – kamalon Dec 12 '16 at 14:40
  • Because `for_who` is typed as a simple `Array`, you have to do the casting to ensure `user_id` is the same type as the elements of `for_who`. That's why I was asking for you to also provide the value of `user_id` and the document your expecting to find. – JohnnyHK Dec 12 '16 at 15:12

1 Answers1

0
Events.find().then((events) => {
  var userData = events.find((v) => {
    return v.for_who === user_id
  })
  if(userData){
    //user was found
  }
})

i think this cloud work

lacexd
  • 903
  • 1
  • 7
  • 22
  • I think you didn`t understand my question. I want to get events by user_id. The users have access to see the event, defined in "for_who" array in database – kamalon Dec 12 '16 at 14:38
  • it does what you wanted. gets all the records and then filters them based on the given user. its working but not the way you wanted – lacexd Dec 12 '16 at 15:25