MEAN STACK: Mongoose model blocks communication with my controller

Asked

Viewed 123 times

-1

Man controller does not send data to my router when mine Model is being exported in the application and I don’t know why it happens.

controller js.

var Model = require('../models/dado.js');

exports.listaDados = function(req, res) {
  Model.find({}, function(erro, lista) {
    if(erro) console.log(erro);
    res.json(lista);
  });
};

dice js.

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var schema = new Schema({
  nome: {type: String, required: true},
  idade: {type: Number, required: true, index: {unique: false}}
});

module.exports = mongoose.model('Dado', schema);

package json.

{
  "name": "teste",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.6",
    "express": "^4.15.3",
    "express-load": "^1.1.15",
    "method-override": "^2.3.9",
    "mongodb": "^2.2.27",
    "mongoose": "^4.10.4"
  }
}

js router.

var controller = require('../controllers/controller');

module.exports = function(app) {
  app.get('/dados', controller.listaDados);
};

If I comment on the part of the code that exports the Model, guy:

//module.exports = mongoose.model('Dado', schema);

Man controller works well, I can even send static data from server for the customer, however I need the Model to get the database data.

Note: Mongoose connects normal, everything works ok except this part.

  • When leaving the model have no error in the console? Tried instead of commenting on the line that exports the model comment the Model.find()? Instead of directly exporting the model, try exporting a function that returns the model, like this: module.exports = function() { // todo o código dado.js..return mongoose.model('Dado', schema); }

1 answer

1

By the code shown on the github Gist link, the Mongoose configuration file is missing.

Your given file, is missing make the require of your Mongoose configuration file.

ex: var db = require('./meu_arquivo_de_config_do_mongo');

Getting something similar to this.

var db = require('./meu_arquivo_de_config_do_mongo');
var mongoose = require('mongoose');
var dadoSchema = new mongoose.Schema({
    // ...
});

module.exports = db.model('Dado',  dadoSchema);

Note that you create a new Schema to add the existing instance of Mongoose. In the previous code you do not pass this instance to anyone.

Browser other questions tagged

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