Use more than one schema per collection on mongodb
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.
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 },
When no collection argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use mongoose.pluralize(), or set your schemas collection name option.
const schema = new Schema({ name: String }, { collection: 'actor' });// orschema.set('collection', 'actor');// orconst collectionName = 'actor'const M = mongoose.model('Actor', schema, collectionName)