0

In my mongodb database there are 4 collections.I can retrive data using each collection on by one.Now How can retrieve data from different collections in same code using key word like findone,getAll ?My model.js given below.DB ->mongodb backend ->nodeexpress

model1.js


const Schema=mongoose.Schema;
const customerSchema = new Schema({

    shop:{
        type : String,
        required : true,
    },
    name:{
        type : String,
        required : true,
    },

    area:{
        type : String,
        required : true,
    },
       {
    timestamps : true
    }
);
const Customer = mongoose.model('customers',customerSchema);
module.exports = Customer;

model2.js

const mongoose = require('mongoose');

const Schema=mongoose.Schema;
const distributorSchema = new Schema({


    fullName:{
        type : String,
        required : true,
    },
    warehouse:{
        type : String,
        required : true,
    },
   phoneNo:{
        type : String,
        required : true,
    },

    password:{
        type : String,
        required : true
    }
},
    {
    timestamps : true
    }
);
const Distributor = mongoose.model('distributors',distributorSchema);
module.exports = Distributor;



2
  • Do you want to retreive all data from all collections in the db? Commented Jan 15, 2020 at 10:23
  • No. just 2 collections in db Commented Jan 15, 2020 at 10:24

1 Answer 1

1

You can make function in your controller.js like this

export async function getDataFromTwoCollections(){

  let allData = {modelOneData : [], modelTwoData : []};
  let modelOneData = await Customer.find({}).exec();
  let modelTwoData = await Distributor.find({}).exec();
  allData.modelOneData = modelOneData 
  allData.modelTwoData  = modelOneData
  return allData
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fahad Hassan answer was very useful..Js file worked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.