Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

node.js - Use more than one schema per collection on mongodb

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:

OverwriteModelError: Cannot overwrite allUsers model once compiled.
OverwriteModelError: Cannot overwrite checkInOut model once compiled.


Heres my 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
   };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...