Model, Express and the Mongoose

Asked

Viewed 662 times

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 make the models available in my application, start together with the server. Since, with this implementation, express does not see the 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.

2 answers

1


I believe you do not need to load all modules if importing them only when you need to use them. Example of User model:

const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true
  },
  password: {
    type: String,
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
})

module.exports = mongoose.model('User', UserSchema)

As you’ve uploaded controllers, I’ll assume you’ll use one of them. Here’s another example of a possible Usercontroller:

const User = require('../models/User')

class UserController {
  async store (req, res) {
    const { email } = req.body

    if (await User.findOne({ email })) {
      return res.status(400).json({ error: 'User already exists' })
    }

    const user = await User.create(req.body)

    return res.json(user)
  }
}

module.exports = new UserController()

I believe that this example should be enough to help you with this little problem.

0

First, I suggest you stop using express-load, as it does not run well with ES6 classes. Use the consign.

I guess to answer that question, I’d need the contents of the file '../models/productModel', that you omitted.

But I assure you that it is very easy to work with Mongoose. I suggest following the basic guide on https://mongoosejs.com/.

And if you don’t adapt to a ORM like Mongoose, you can always use the mongodb driver directly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.