mongoose連接collection後自動加s的問題

這兩天折騰mongoose,發現數據成功寫入集合了,但是在Terminal查詢的時候卻查不到
於是show collections後發現在原來的集合底下,又生成了一個加了s的集合,shenmegui

查了一下,發現是mongoose.model()的問題

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

在官方的api文檔裏面有解釋(我不聽)

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don’t like this behavior, either pass a collection name or set your schemas collection name option.

當沒有傳入collection參數時,Mongoose會通過model name(就是第一個參數),調用utils.toCollectionName方法產生一個collection name,而這個方法會使name變成複數形式。如果你不想要這個過程,只要傳入collection name參數或設置Schema中的collection name選項。

就像這樣:

var schema = new Schema({ name: String }, { collection: 'actor' });

// or

schema.set('collection', 'actor');

// or

var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName);

什麼坑爹設定…

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章