node.js 在 mongodb 上为每个集合使用多个架构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14453864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:59:46  来源:igfitidea点击:

Use more than one schema per collection on mongodb

node.jsmongodbmongooseschema-designnosql

提问by TaLha Khan

I wanted to use more than one schema per collection in mongodb , how to use it....?
It gives me this error when I try to run it:

Error:

我想在 mongodb 中为每个集合使用多个模式,如何使用它....?
当我尝试运行它时,它给了我这个错误:

错误:

OverwriteModelError: Cannot overwrite allUsersmodel once compiled.
OverwriteModelError: Cannot overwrite checkInOutmodel once compiled.

OverwriteModelError:allUsers编译后无法覆盖模型。
OverwriteModelError:checkInOut编译后无法覆盖模型。


Heres my schema.js


这是我的 schema.js

   var mongoose = require('mongoose');

      var Schema = mongoose.Schema
          , ObjectId = Schema.ObjectId;

   var checkInInfoSchema= new Schema({
       name:String,
       loginSerialId:Number
   });


   var loginUserSchema = new Schema({
          sn : { type: Number, unique:true }
          ,uname: {type:String, unique:true}
          ,pass:String
      });

   var registerUserSchema = new Schema({
       sn : { type: Number, unique:true }
       , name: String   //his/her name
       ,pass:String,
       companyKey:{type:String},
       uname:{type:String,unique:true}
   });



   var checkInOutSchema = new Schema({
       uname: String
       ,companyKey:String
       ,task:String
       ,inTime:String
       ,outTime:String
       ,date:{type:String}
       ,serialId:{type:Number,unique:true}
       ,online:Boolean
   });

   //Different schema for same collection "allUsers"        
   var allUser=mongoose.model('allUsers',loginUserSchema);        
   var registerUser=mongoose.model('allUsers',registerUserSchema);

    //Different schema for same collection "checkInOut"
   var checkInOut=mongoose.model('checkInOut',checkInOutSchema);
   var checkInInfo=mongoose.model('checkInOut',checkInInfoSchema);

   module.exports={

       allUser:allUser, 
       registerUser:registerUser,

       checkInOut:checkInOut,
       checkInInfo:checkInInfo
   };

回答by Julián Duque

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-modelor you can see the following gistit might help.

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

回答by sarah

I tried the selected answer but when querying on specific model object, it retrieves data of both schemas. So I think using discriminator yields better solution:

我尝试了选定的答案,但是在查询特定模型对象时,它会检索两种模式的数据。所以我认为使用鉴别器会产生更好的解决方案:

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));

Example output:

示例输出:

{ __type: 'CoordinateModel', // discriminator field
    _id: 5adddf0367742840b00990f8,
    lat: '40',
    longt: '20',
    name: 'coordsOfHome',
    __v: 0 },