如何在猫鼬中声明集合名称和模型名称 [英] How to declare collection name and model name in mongoose
问题描述
我有3种记录,
1)Categories,
2)Topics and
3)Articles
在我的mongodb中,我只有1个名为类别"的集合,在其中处理了以上3种类型的文档.
In my mongodb, i have only 1 colection named 'categories' in which i stroe the above 3 types of documents.
对于这3个模块,我以如下方式编写了3个模型(每个模型一个),
For these 3 modules,i wrote 3 models(one each) in such a way like below,
mongoose.model('categories', CategorySchema);
mongoose.model('categories', TopicSchema)
mongoose.model('categories', ArticlesSchema)
like .... mongoose.model('collection_name',Schema_name)
like....mongoose.model('collection_name', Schema_name)
但是当我运行我的代码时,它会抛出错误
but when i run my code ,it throws error that
Cannot overwrite `categories` model once compiled.
如果我这样更改上述型号,
If i change the above models like this,
mongoose.model('category','categories', CategorySchema);
mongoose.model('topics','categories', TopicSchema)
mongoose.model('articles','categories', ArticlesSchema)
它正在创建2个我不想要的名为主题和文章的集合. 这是我现在的问题,任何人都可以建议我帮忙.....谢谢....
It is creating 2 collections named topics and articles which i dont want. This is my issue right now,can anyone suggest me help.....Thanks....
推荐答案
Try-
mongoose.model('category', CategorySchema, 'categories');
mongoose.model('topics', TopicSchema, 'categories');
mongoose.model('articles', ArticlesSchema, 'categories');
如文档中所述: http://mongoosejs.com/docs/api.html #index_Mongoose-model
猫鼬#model(名称,[模式],[集合],[skipInit])
Mongoose#model(name, [schema], [collection], [skipInit])
定义或检索模型.
参数:
- 第一个参数-名称< String>型号名称
- 第二个参数-[模式]<模式>模式名称
- 第3个参数-[集合]< String>集合名称(可选,由模型名称得出)
- 第4个参数-[skipInit]< Boolean>是否跳过初始化(默认为false)
- 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)
请参阅- https://stackoverflow.com/a/14454102/3896066
这篇关于如何在猫鼬中声明集合名称和模型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!