簡體   English   中英

如何在node.js網站中組織模型?

[英]How to organize models in a node.js website?

我剛剛開始嘗試使用node.js構建網站,並且在組織我的項目模型時遇到問題。

我在Internet上發現的所有現實示例都使用Mongoose。 該庫允許您以靜態方式定義模型。 所以你可以這樣寫:

// models/foo.js
module.exports = require('mongoose').model('Foo', ...);

// app.js
mongoose.connect(...);

// some_controller_1.js
var Foo = require('./models/foo');
Foo.find(...);

// some_controller_2.js
var Foo = require('./models/foo');
Foo.find(...);

但是由於我不想使用MongoDB,因此我需要另一個ORM。 我發現的所有其他ORM都不允許這樣做。 首先需要創建一個實例,然后只有您可以注冊模型。 另外,他們似乎不允許訪問已注冊模型的列表。

所以我嘗試這樣做:

// models/user.js
var registrations = [];
module.exports = function(sequelize) {
    var result = null;
    registrations.forEach(function(elem) {
        if (elem.db == sequelize)
            result = elem.value;
    });
    if (result) return result;


    // data definition
    var user = sequelize.define("User", ...);


    registrations.push({ db: sequelize, value: user });
    return user;
};

我可以這樣使用:

// some_controller_1.js
var Foo = require('./models/foo')(app.get('database'));
Foo.find(...);  // using Foo

但是我必須在每個模型文件上寫的這些小的頁眉和頁腳有點煩人,並且直接違反了“不要重復自己”的原則。 同樣,盡管這不是一個大問題,但這是一種內存泄漏,因為“ sequelize”對象將永遠不會被釋放。

有沒有想到的更好的方法?

您可以在此處找到有關使用sequelize處理模型的文章: http ://sequelizejs.com/articles/express#the-application

基本上,您只需models/index.js如下所述創建一個models/index.jshttp : //sequelizejs.com/articles/express#block-3-line-0

然后,您只需將模型定義放到此處指出的models文件夾中的文件中: http : //sequelizejs.com/articles/express#block-4-line-0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM