简体   繁体   English

如何在 Mongoose 中执行 FIND,然后执行 AND,然后执行 OR 与 POPULATE

[英]How to perform FIND, then perform AND, then perform OR with POPULATE in Mongoose

I have a query that I wish to perform something similar as:我有一个查询,我希望执行类似的操作:

  1. Archive does not exists AND存档不存在并且
  2. Owner Email in schema is in Query OR架构中的所有者 Email 在查询中 OR
  3. Owner Email in Populated's schema is in Query Populated 的架构中的所有者 Email 在 Query 中

Below is what I have tried as of my understanding根据我的理解,以下是我尝试过的

    let docs = await Document.find({ archive: { $exists: false }})
      .and([{ owner_email: { $regex: localQuery } }])
      .or()
      .populate('owner_id', null, {
        email: { $regex: localQuery },
      });

So what I wish to do is, I have two schema, the user and the documents, User sometimes is shared along [as a librarian], then I wish to return, both, which matches the populated email or the actual owner's email.所以我想要做的是,我有两个模式,用户和文档,用户有时与 [作为图书管理员] 共享,然后我希望返回,两者都匹配填充的 email 或实际所有者的 email。

As mongoose's populate() method does not really "join" collections and rather makes another query to the database to populate after the find() operation, you can switch to an aggregation pipeline and use $lookup in order to match the email in the referenced field.由于 mongoose 的populate()方法并没有真正“加入” collections 而是在find()操作后对数据库进行另一个查询以填充,因此您可以切换到聚合管道并使用$lookup以匹配引用中的 email场地。 So assuming your models look like:所以假设你的模型看起来像:

const Document = mongoose.model('Document', {
    name: String,
    archive: String, 
    owner_email: String,
    owner: {type: Schema.Types.ObjectId, ref: 'Person'}
});

const Person = mongoose.model('Person', {
    firstName: String,
    lastName: String,
    email: String
});

Then, you can do:然后,你可以这样做:

const result = await Document.aggregate([
        {
            $lookup: {
                from: Person.collection.name,
                localField: "owner",
                foreignField: "_id",
                as: "referencedOwner"
            }
        },
        {
            $match: {
                archive: {$exists: false},
                $or: [
                    {"referencedOwner.email": {$regex: localQuery}},
                    {"owner_email": {$regex: localQuery}}]
            }
        }
    ]);

Here's a working example on mongoplayground: https://mongoplayground.net/p/NqAvKIgujbm这是 mongoplayground 上的一个工作示例: https://mongoplayground.net/p/NqAvKIgujbm

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

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