How to declare collection name and model name in mongoose

后端 未结 4 1504
死守一世寂寞
死守一世寂寞 2021-02-02 18:26

I have 3 kind of records,

1)Categories,
2)Topics  and
3)Articles 

In my mongodb, i have only 1 colection named \'categories\' in which i stroe

相关标签:
4条回答
  • 2021-02-02 18:54

    "The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name" - directly from the Model docs -- https://mongoosejs.com/docs/models.html

    0 讨论(0)
  • 2021-02-02 18:57

    As you stated, When you write this,

    mongoose.model('categories', CategorySchema);
    mongoose.model('categories', TopicSchema);
    mongoose.model('categories', ArticlesSchema);
    

    The output becomes inappropriate so do this instead,

    mongoose.model('category', CategorySchema);
    mongoose.model('topic', TopicSchema);
    mongoose.model('article', ArticlesSchema);
    

    Bonus tip. Mongoose makes your collection name plural by default so change a little code if you want your collection name as you wrote.

    mongoose.model('category', CategorySchema,'category');
    mongoose.model('topic', TopicSchema,'topic');
    mongoose.model('article', ArticlesSchema,'article');
    
    0 讨论(0)
  • 2021-02-02 19:02

    Try-

    mongoose.model('category', CategorySchema, 'categories');
    mongoose.model('topics', TopicSchema, 'categories');
    mongoose.model('articles', ArticlesSchema, 'categories');
    

    As mentioned in docs: http://mongoosejs.com/docs/api.html#index_Mongoose-model

    Mongoose#model(name, [schema], [collection], [skipInit])

    Defines a model or retrieves it.

    Parameters:

    • 1st param - name <String> model name
    • 2nd param - [schema] <Schema> schema name
    • 3rd param - [collection] <String> collection name (optional, induced from model name)
    • 4th param - [skipInit] <Boolean> whether to skip initialization (defaults to false)

    See - https://stackoverflow.com/a/14454102/3896066

    0 讨论(0)
  • 2021-02-02 19:08

    You can use Mongoose Discriminators (http://mongoosejs.com/docs/discriminators.html) for that.

    This article has a good and easy example of how to do that: https://docs.microsoft.com/en-us/azure/cosmos-db/mongodb-mongoose#using-mongoose-discriminators-to-store-data-in-a-single-collection.

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