0

I have an collection with documents that can be public or private. I am looking to have a single query that can get a document by an _id and check if it's private. If it is private it needs to check if the user requesting the document is a participant in the object.

Here is the object:

    {
    "_id" : ObjectId("5769ae620e80ea1c7f8a997f"),
    "owner" : ObjectId("5740edae95a1b4c043d033df"),
    "private" : false,
    "participants" : [
        {
            "uid" : ObjectId("5740edae95a1b4c043d033df"),
            "notify" : true
        }
    ],
    "messages" : [ ]
}

This is the 2 step query I wrote and wondering if I can simplify it

function getRoom(roomId, user){

    db.rooms.findOne({ _id: pmongo.ObjectId(roomId) })
        .then(room => {
          if(room.private){
            return db.rooms.findOne({
              _id: pmongo.ObjectId(roomId),
              participants: {$eleMatch: {uid: String(user._id)}}
            })
          } else {
            return room
          }
        })

    }

Any help would be great!

1 Answer 1

3

MongoDB has $or operator which can be used in this case:

db.rooms.findOne({ $or: [
  {
    _id: pmongo.ObjectId(roomId),
    private: { $ne: true }
  }, {
    _id: pmongo.ObjectId(roomId),
    participants: {$eleMatch: {uid: String(user._id)}}
  }
]})
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Let me give that a shot!
Yes, it should give a little more speed but if property private will be empty it will fails so there should be the default value in a Room model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.