Node.js 使用node express从mongodb检索数据
在我的mongodb数据库中有4个集合。我可以一个一个地使用每个集合检索数据。现在 如何使用关键字(如findone、getAll)从同一代码中的不同集合检索数据?My model.js如下所示.DB->mongodb backend->nodeexpress model1.jsNode.js 使用node express从mongodb检索数据,node.js,mongodb,express,Node.js,Mongodb,Express,在我的mongodb数据库中有4个集合。我可以一个一个地使用每个集合检索数据。现在 如何使用关键字(如findone、getAll)从同一代码中的不同集合检索数据?My model.js如下所示.DB->mongodb backend->nodeexpress model1.js const Schema=mongoose.Schema; const customerSchema = new Schema({ shop:{ type : String,
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;
您可以像这样在
controller.js
中创建函数
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
}
是否要检索数据库中所有集合的所有数据?否。dbFahad Hassan中只有2个集合的答案非常有用..Js文件工作正常