Reputation: 171
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;
Upvotes: 0
Views: 47
Reputation: 811
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
}
Upvotes: 1