如何在get()函数中实现多个集合? [英] How to implement more than one collection in get() function?

查看:50
本文介绍了如何在get()函数中实现多个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型 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);

我的 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;

如何在此 get()函数中实现多个集合?我将集合名称放入模型中.请为我提供一个在 get()函数中调用多个集合的解决方案.

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.

推荐答案

以下是为一个模式使用多个集合名称的示例:

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 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.

有关更多信息,请参阅文档: http://mongoosejs.com/docs/api.html#index_Mongoose-model ,或者您可以看到以下要点可能会有帮助.

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.

这篇关于如何在get()函数中实现多个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆