Mongoose - Same schema for different collections in (MongoDB)

后端 未结 1 1577
野趣味
野趣味 2021-01-01 19:00

I\'m creating an application (Express+MongoDB+Mongoose) where documents are naturally clustered by groups. Every query to the database will only need to access documents fro

相关标签:
1条回答
  • 2021-01-01 19:26

    Models are already cached by Mongoose and you can use the same schema object for multiple models/collections. So just create your set of models once (at startup) using code like:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var schema = new Schema({...});
    var model1 = mongoose.model('model1', schema);
    var model2 = mongoose.model('model2', schema);
    

    If you don't want to pass around the model1, model2 model instances, you can look them up as needed by calling mongoose.model('model1'); in your handlers.

    0 讨论(0)
提交回复
热议问题