简体   繁体   English

如果条件查询mongo db

[英]If condition query for mongo db

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. 我正在寻找一个可以通过_id获取文档并检查其是否私有的查询。 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! 任何帮助将是巨大的!

MongoDB has $or operator which can be used in this case: MongoDB具有$or运算符,可以在这种情况下使用:

db.rooms.findOne({ $or: [
  {
    _id: pmongo.ObjectId(roomId),
    private: { $ne: true }
  }, {
    _id: pmongo.ObjectId(roomId),
    participants: {$eleMatch: {uid: String(user._id)}}
  }
]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM