2017-06-07 15 views
1

您可以檢索模型貓鼬像這樣:獲取(聯想)貓鼬車型的陣列

提醒用戶= mongoose.model(「用戶」);我想要得到這些模型的關聯數組。 有沒有一些聰明的方法來獲取使用對象解構的模型列表?喜歡的東西:

const {User, Employees, Managers} = mongoose.model('x'); 

我目前的解決方案是這樣:

/project 
    /models 
    index.js 

其中index.js看起來像:

module.exports = { 
    User: require('./user'), 
    Employee: require('./employee'), 
    Manager: require('./manager'), 
}; 

凡user.js的,employee.js和經理.js文件看起來像:

let mongoose = require('mongoose'); 
let Schema = mongoose.Schema; 

let userSchema = new Schema({...}); 

module.exports = mongoose.model('User', userSchema, 'users'); 

然後,我可以這樣做:

const {User, Employees, Managers} = require('./models'); 

但是我正在尋找一個更好的解決方案,無需手動工作,如果可能的。

回答

2
const models = {}; 
mongoose.modelNames().forEach(function(modelName){ 
    models[modelName] = mongoose.model(modelName); 
}); 
console.log(models); 
+0

這將工作,但爲了避免簡單的競爭條件,我可能仍然需要在這裏手動導入代碼上方的每個模型。 –

+0

你能舉一個比賽條件的例子嗎?我認爲你不需要獨立導入文件,模型可以被上面的代碼訪問和安全地使用。我可能是錯的。 –

+0

在我們的應用程序和大多數真實應用程序中,文件的加載順序非常複雜。在任何代碼在你的答案中調用代碼之前,必須確保所有模型都加載,不那麼容易。 –