Home > Back-end >  How to find documents by a field from a ref?
How to find documents by a field from a ref?

Time:09-17

Suppose I have the following two schemas:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schemaA = new Schema({
    tag: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'schemaB',
        },
    ],
});

module.exports = SchemaA = mongoose.model('schemaA', schemaA);
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schemaB = new Schema({
    name: {
        type: String,
    }
});

module.exports = SchemaB = mongoose.model('schemaB', schemaB);

How can I find all documents in SchemaA that have their tag field match the name of SchemaB?

I know that if I had the _id of SchemaB, I'd be able to do this as,

const schemaBId = 'some-_id-string'
const docs = await SchemaA.find({ tag: schemaBId })

But how can I do this, if I only have the name value?

CodePudding user response:

You can try using mongoose populate() function it might help you achieve exactly what you want. Here is the populate docs for quick reference.

CodePudding user response:

first use lookup to get data of ModelB and then put these data as t after that make query with match to find where name of ModelB is test

ModelA.aggregate([
    {
        $lookup: {
            from: 'collectionB',
            localField: 'tag',
            foreignField: '_id',
            as: 't',
        },
    },
    {
        $match: { 't.name': 'test' },
    },
]);
  • Related