简体   繁体   中英

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
  3. Owner Email in Populated's schema is in 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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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