How to implement more than one collection in get()

2019-08-27 12:02发布

问题:

My model university.js

const mongoose = require('mongoose');

const UniversitySchema = mongoose.Schema({
    worldranking:String,
    countryranking:String,
    universityname:String,
    bachelorprogram:String,
    masterprogram:String,
    phdprogram:String,
    country:String
},{collection:'us'});

const University =module.exports = mongoose.model('University',UniversitySchema);

My route.js

const express = require('express');
const router = express.Router();
const University = require('../models/university');



//retrieving data
//router.get('/universities',(req,res,next)=>{
  //  University.find(function(err,universities){
    //    if(err)
      //  {
        //    res.json(err);
        //}
       // res.json(universities);
    //});
//});

router.get('/usa',function(req,res,next){
  University.find()
   .then(function(doc){
     res.json({universities:doc});
   });
});


module.exports= router;

How to implement multiple collections in this get() function? I put my collection name in the model. Please help me with a solution to call multiple collections in get() function.

回答1:

Here is Example to use multiple collection names for one schema:

const coordinateSchema = new Schema({
  lat: String,
  longt: String,
  name: String
}, {collection: 'WeatherCollection'});

const windSchema = new Schema({
 windGust: String,
 windDirection: String,
 windSpeed: String
}, {collection: 'WeatherCollection'});

//Then define discriminator field for schemas:
const baseOptions = {
  discriminatorKey: '__type',
  collection: 'WeatherCollection'
};

//Define base model, then define other model objects based on this model:
const Base = mongoose.model('Base', new Schema({}, baseOptions));
const CoordinateModel = Base.discriminator('CoordinateModel', coordinateSchema);
const WindModel = Base.discriminator('WindModel', windSchema);

//Query normally and you get result of specific schema you are querying:
mongoose.model('CoordinateModel').find({}).then((a)=>console.log(a));

In Short,

In mongoose you can do something like this:

var users = mongoose.model('User', loginUserSchema, 'users');
var registerUser = mongoose.model('Registered', registerUserSchema, 'users');

This two schemas will save on the 'users' collection.

For more information you can refer to the documentation: http://mongoosejs.com/docs/api.html#index_Mongoose-model or you can see the following gist it might help.

Hope this may help you. You need to modify according to your requirements.