我在模型文件夹中创建了一个db.js和empleado.js。我可以连接到db.js,但不能连接到empleado.js。我在empleado.js中导出该连接但控制台显示以下错误:
$ node app
C:\Users\Dario\documents\02 - trabajo\97 - proyectos\test\app.js:14
empleado.setConnection(db);
^
TypeError: empleado.setConnection is not a function
at Object.<anonymous> (C:\Users\Dario\documents\02 - trabajo\97 - proyectos\
test\app.js:14:10)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var db = require('./model/db'); // DataBase Connection
var empleado = require('./model/empleado'); // Employee Data Model
empleado.setConnection(db);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade'); // Utilizo Jade para vas views (vistas)
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); // Activamos un directorio de archivos estáticos
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
db.js
// Integro mongoose al proyecto
var mongoose = require('mongoose');
// Archivo de configuración de la Base de Datos
var config = require('../config/db');
// Armo el string de conección de la Base de Datos
var dbURI = 'mongodb://' + config.host + '/' + config.db;
// Conecto la Base de Datos
var db = mongoose.connect(dbURI);
// Gestionando eventos de conección a la Base de Datos
db.connection.on('connected', function () {
console.log('Mongoose conectado a ' + dbURI);
});
db.connection.on('error',function (err) {
console.log('Mongoose error de conección: ' + err);
});
db.connection.on('disconnected', function () {
console.log('Mongoose desconectado');
});
process.on('SIGINT', function() {
db.connection.close(function () {
console.log('Mongoose desconectado por finalización de la aplicación');
process.exit(0);
});
});
module.exports = db;
empleado.js
var mongoose = require('mongoose');
exports.setConnection = function(connection) {
mongoose = connection;
}
var empSchema = new mongoose.Schema ({
nombre: String,
apellidos: String
});
var empModelo = mongoose.model('Empleado', empSchema, 'empleados');
module.exports = empModelo;
提前致谢。 我是mongoDB,Mongoose和NodeJS的新手
答案 0 :(得分:0)
I think that the best approach here would be passing mongoose when requiring empleado.js
:
var empleado = require('./model/empleado')(mongoose);
Then you don't need to have a setConnection method.
Your empleado.js
file would be like:
module.exports = function(mongoose) {
var empSchema = new mongoose.Schema ({
nombre: String,
apellidos: String
});
return mongoose.model('Empleado', empSchema, 'empleados');
};