Wednesday, 7 June 2017

Mongoose - Differents output by $or

I've a problem, I've a model like this:

UserSchema = {
  name: String
}

A resource model like this:

ResourceSchema = {
  owner: mongoose.Schema.Types.ObjectId // User id owner
  name: String
}

And an access model like this:

UserAccessSchema = {
  owner: mongoose.Schema.Types.ObjectId, // User id Owner
  destination: mongoose.Schema.Types.ObjectId, // User id Destination,
  shared: mongoose.Schema.Types.ObjectId // Shared resource by onwer to destination
}

I'd like to find all resource that user owns and resource shared to him with UserAccessSchma (user_id === UserAccessSchema.destination).

So I'm doing something like this:

UserAccessSchema.find({destination: currentUser._id}, function (err, accesses) {
  let resourceAccessList = []
  accesses.forEach(function (e) {
    resourceAccessList = resourceAccessList.concat(e.shared);
  });
  ResourceSchema.find({
    $or: [
      {
        owner: currentUser._id
      },
      {
        _id: {$in: resourceAccessList}
      }
    ]
  }).exec(function(err, resources) {
    // Do something with resources
  })
})

But: I'd like have returned objects contains attribute like 'byAccessSchema' to specify if the object has been acquiered because I'm the owner or if this is a shared resource.

PS: I know, I can check if currentUser._id === resource.owner to check it, but i'd like to do something more complex after that.

Thanks in advance ! Have a nice day !! :)



via hayato

No comments:

Post a Comment