Model, Express and Mongoose

0

I have the following code in express.js

const express = require('express');
const load = require('express-load');

module.exports = () => {

var app = express();
var bodyParser = require('body-parser');

//variável de ambiente
app.set('port', 3000);

//middleware
app.use(express.static('./public'));
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}) );

app.use(require('express-method-override') () );

//template engine
app.set('view engine', 'ejs');

//templates
app.set('views', './src/views');

load('models', {cwd: 'src'} )
    .then('controllers')
    .then('routes')
    .into(app);

return app;

}

Database.js file

var mongoose = require('mongoose');

module.exports = (uri) => {
mongoose.connect(uri);

//const Product = require('../models/productModel')

mongoose.connection.on('connected', ()=> {
    console.log('Mongoose! Conectado em ' + uri);
});

mongoose.connection.on('disconected', ()=> {
    console.log('Mongoose! Desconectado em ' + uri);
});

mongoose.connection.on('error', (erro)=> {
    console.log('Mongoose! Erro na conexao em ' + erro);
});

process.on('SIGINT', ()=> {
    mongoose.connection.close( ()=> {
        console.log('Mongoose! Desconectado. Aplicacao encerrada');
        process.exit(0);
    });
});

}

server.js

var http  = require('http');
var app = require('./config/express')();

require('./config/database.js')('mongodb://{minhaconexao}');

http.createServer(app).listen(app.get('port'), () => {
    console.log('Express Server escutando na porta ' + app.get('port'));
});

I would like to know how I can make the models available in my application, go together with the server. Since, with this implementation, express does not see models.

In the database file, if I remove the comment, the product model is created. I have a few days of NodeJS + Express and Mongoose, so some things still seem confusing to me.

    
asked by anonymous 13.03.2018 / 21:55

1 answer

0

First, I suggest to stop using express-load, since it does not work well with ES6 classes. Use consign .

I think to answer this question, I would need the contents of the file '../models/productModel' , which you omitted.

But I assure you that it is very easy to work with mongoose. I suggest following the basic guide at link .

And if you do not adapt to an ORM like mongoose, you can always use the mongodb driver > directly.

    
10.09.2018 / 20:56