1

I'm a beginner in the MEAN world, and I hope to progress quickly thanks to the StackOverflow community.

Here is my problem: I want to retrieve all the information contained in 2 models thanks to 2 fields. Here are my templates :

module.exports = mongoose => {
    var schema = mongoose.Schema(
      {
        fieldA: String,
        fieldB: String,
        fieldC: String,
        fieldD: String,
        fieldE: String
      },
      { timestamps: true }
    );

    schema.method("toJSON", function() {
      const { __v, _id, ...object } = this.toObject();
      object.id = _id;
      return object;
    });

    const ModelA = mongoose.model("ModelA", schema);
    return ModelA;
  };


  module.exports = mongoose => {
    var schema = mongoose.Schema(
      {
        field1: String,
        field2: String,
        field3: String,
        field4: String,
        field5: String
      },
      { timestamps: true }
    );

    schema.method("toJSON", function() {
      const { __v, _id, ...object } = this.toObject();
      object.id = _id;
      return object;
    });

    const ModelB = mongoose.model("ModelB", schema);
    return ModelB;
  };

I want to retrieve in my controller, all the fields of modelA and modelB where modelA.fieldA = modelB.field4 AND modelA.fieldD=modelB.field1

I can't figure out how to code the controller to solve my problem :

const db = require("../models");
const ModelA = db.modelA;
const ModelB = db.modelB;

exports.findAll = (req, res) => {
  ModelA.find()
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving customers."
      });
    });
};

Thank you for your help.

ZeeCos
  • 51
  • 1
  • 8
  • 1
    Does this answer your question? [Mongodb aggregation lookup with conditions](https://stackoverflow.com/questions/48518215/mongodb-aggregation-lookup-with-conditions). You can use that which is MongoDB's native or mongoose's func `.populate()` which works similar to `$lookup`. – whoami - fakeFaceTrueSoul Apr 15 '20 at 18:10
  • Thank you, but I can't get back what I want. – ZeeCos Apr 15 '20 at 19:33
  • You can edit this question with what you've tried & what is the error that you're getting or any issue that you're seeing.. – whoami - fakeFaceTrueSoul Apr 15 '20 at 19:36

0 Answers0