Program Club

Mongoose 및 NodeJS 프로젝트의 파일 구조

proclub 2020. 12. 14. 20:07
반응형

Mongoose 및 NodeJS 프로젝트의 파일 구조


현재 Mongoose / NodeJS 애플리케이션의 /models/models.js 파일에 모든 모델 (스키마 정의)이 있습니다.

user_account.js, profile.js 등과 같은 다른 파일로 분리하고 싶습니다. 그러나 컨트롤러가 분리되고 " 모듈을 찾을 수 없음 "을보고하기 때문에 그렇게 할 수없는 것 같습니다 .

내 프로젝트 구조는 다음과 같습니다.

/MyProject
  /controllers
    user.js
    foo.js
    bar.js
    // ... etc, etc
  /models
    models.js
  server.js

내 models.js 파일의 내용은 다음과 같습니다.

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

mongoose.connect('mongodb://localhost/mydb');

var UserAccount = new Schema({
    user_name       : { type: String, required: true, lowercase: true, trim: true, index: { unique: true } }, 
    password        : { type: String, required: true },
    date_created    : { type: Date, required: true, default: Date.now }
}); 

var Product = new Schema({
    upc             : { type: String, required: true, index: { unique: true } },
    description     : { type: String, trim: true },
    size_weight     : { type: String, trim: true }
});

내 user.js 파일 (컨트롤러)은 다음과 같습니다.

var mongoose    = require('mongoose'), 
    UserAccount = mongoose.model('user_account', UserAccount);

exports.create = function(req, res, next) {

    var username = req.body.username; 
    var password = req.body.password;

    // Do epic sh...what?! :)
}

스키마 정의를 여러 파일로 나누고 컨트롤러에서 참조하려면 어떻게해야합니까? 참조 할 때 (스키마가 새 파일에있는 후)이 오류가 발생합니다.

* 오류 : 스키마가 "user_account"모델에 등록되지 않았습니다. *

생각?


다음은 샘플입니다. app/models/item.js

var mongoose = require("mongoose");

var ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    index: true
  },
  equipped: Boolean,
  owner_id: {
    type: mongoose.Schema.Types.ObjectId,
    index: true
  },
  room_id: {
    type: mongoose.Schema.Types.ObjectId,
    index: true
  }
});

var Item = mongoose.model('Item', ItemSchema);

module.exports = {
  Item: Item
}

에서 항목 컨트롤러에서이 문제를로드하려면 app/controllers/items.js내가 할 것

  var Item = require("../models/item").Item;
  //Now you can do Item.find, Item.update, etc

즉, 모델 모듈에서 스키마와 모델을 모두 정의한 다음 모델 만 내 보냅니다. 상대 요구 경로를 사용하여 모델 모듈을 컨트롤러 모듈에로드합니다.

연결하려면 서버 시작 코드 ( server.js또는 기타) 에서 초기에 처리하십시오 . 일반적으로 구성 파일 또는 환경 변수에서 연결 매개 변수를 읽고 구성이 제공되지 않으면 기본적으로 개발 모드 localhost로 설정됩니다.

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');

여기에 몇 가지 답변이 실제로 대체 접근 방식을 개발하는 데 도움이되었습니다. 원래 질문은 스키마 정의 만 분리 하는 것이지만, 동일한 파일에 스키마 및 모델 정의를 번들로 묶는 것을 선호합니다.

이것은 대부분 Peter의 아이디어이며, module.exports를 재정 의하여 모델 정의를 내보내는 것만으로 컨트롤러에서 모델에 액세스하는 것을 조금 덜 장황하게 만듭니다.

프로젝트 레이아웃 :

MyProject
  /controllers
    user.js
    foo.js
    bar.js
    // ... etc, etc
  /models
    Item.js
  server.js

models / Item.js는 다음과 같습니다.

var mongoose = require("mongoose");

var ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    index: true
  }
});

module.exports = mongoose.model('Item', ItemSchema); 
// Now `require('Item.js')` will return a mongoose Model,
// without needing to do require('Item.js').Item

그리고 컨트롤러에서 모델에 액세스합니다 (예 : user.js).

var Item = require(__dirname+'/../models/Item')

...

var item = new Item({name:'Foobar'});

server.js 또는 적절하다고 생각되는 곳에서 mongoose.connect (..)를 호출하는 것을 잊지 마십시오!


나는 최근에이 같은 문제와 관련하여 Quora 질문에 대답했습니다. http://qr.ae/RoCld1

내가 매우 훌륭하고 필요한 호출 의 양을 줄이는 것은 모델을 단일 디렉토리로 구조화하는 것입니다. 파일 당 모델이 하나만 있는지 확인하십시오.

모델과 동일한 디렉토리에 index.js 파일을 만듭니다. 이 코드를 추가하십시오. 필요한 fs 를 추가 해야합니다.

var fs = require('fs');

/*
 * initializes all models and sources them as .model-name
 */
fs.readdirSync(__dirname).forEach(function(file) {
  if (file !== 'index.js') {
    var moduleName = file.split('.')[0];
    exports[moduleName] = require('./' + moduleName);
  }
});

이제 다음과 같이 모든 모델을 호출 할 수 있습니다.

var models = require('./path/to/models');
var User = models.user;
var OtherModel = models['other-model'];

Peter Lyons는 근거를 거의 다뤘습니다.
위의 예 (스키마 뒤의 줄 제거)에서 빌려서 다음을 추가하고 싶었습니다.

app/models/item.js

note: notice where `module.exports` is placed
var mongoose = require("mongoose");

var ItemSchema = module.exports = new mongoose.Schema({
  name: {
    type: String,
    index: true
  },
  ...

});

로드하려면 app/controllers/items.js

var mongoose = require('mongoose');
var Item = mongoose.model('Item', require('../models/item'));  

module.exports또는 없는 또 다른 방법 require:

app/models/item.js

var mongoose = require("mongoose");

var ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    index: true
  },
  ... 

});

mongoose.model('Item', ItemSchema); // register model

에서 app/controllers/items.js

var mongoose = require('mongoose')
  , Item = mongoose.model('Item');  // registered model

sequelize-cli에서 영감을 받아 모든 스키마를 정의하는 models 디렉토리가 있습니다.

github에서 전체 앱 : https://github.com/varunon9/node-starter-app-mongo

models / index.js-

'use strict';

const fs        = require('fs');
const path      = require('path');
const mongoose = require('mongoose');//.set('debug', true);
const basename  = path.basename(__filename);
const env       = process.env.NODE_ENV || 'development';
const config    = require(__dirname + '/../config/config.json')[env];
const db        = {};

const Schema = mongoose.Schema;

fs
    .readdirSync(__dirname)
    .filter(fileName => {
        return (
            fileName.indexOf('.') !== 0) 
                    && (fileName !== basename) 
                    && (fileName.slice(-3) === '.js'
        );
    })
    .forEach(fileName => {
        const model = require(path.join(__dirname, fileName));
        const modelSchema = new Schema(model.schema);

        modelSchema.methods = model.methods;
        modelSchema.statics = model.statics;

        // user.js will be user now
        fileName = fileName.split('.')[0];
        db[fileName] = mongoose.model(fileName, modelSchema);
    });

module.exports = db;

models / user.js-

'use strict';

module.exports = {
    schema: {
        email: {
            type: String,
            required: true,
            unique: true,
        },
        mobile: {
            type: String,
            required: false
        },
        name: {
            type: String,
            required: false
        },
        gender: {
            type: String,
            required: false,
            default: 'male'
        },
        password: {
            type: String,
            required: true
        },
        dob: {
            type: Date,
            required: false
        },
        deactivated: {
            type: Boolean,
            required: false,
            default: false
        },
        type: {
            type: String,
            required: false
        }
    },

    // instance methods goes here
    methods: {

    },

    // statics methods goes here
    statics: {
    }
};

참고 URL : https://stackoverflow.com/questions/9230932/file-structure-of-mongoose-nodejs-project

반응형