【发布时间】:2015-01-07 04:29:52
【问题描述】:
我正在使用 Node、Express 和 Mongo 构建一个 API。对于我的数据建模,我使用的是 Mongoose。我想将我的模型移动到我的 API 使用的单独节点模块,以便我也可以在其他项目中重用这些模型。但是,我在 API 中使用 Mongoose 数据模型时遇到了一个奇怪的问题。
当我的数据模型源位于 NPM 模块中时,我的模型无法访问我的数据库,并且任何 .find() 或 .save() 调用都会挂起并且什么也不做。但是,如果我的数据模型源直接存在于我的项目中,而不是在 node_modules 下,那么一切都很好。这是我的代码:
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/myproject-dev'
mongoose.connect(dbURI);
mongoose.connection.on('error', console.error.bind(console, 'database connection error:'));
var productModel = require('myproject-core').models.product;
console.log(productModel);
这里 console.log() 显示(我剪掉了很多东西):
{ [Function: model]
base:
{ connections: [ [Object] ],
plugins: [],
models: ...
...
db:
...
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
但是,如果我 require() 源代码中的模型(具有完全相同的模型代码)
var playerModel = require('./models/player');
console.log(playerModel);
我看到了:
{ [Function: model]
base:
{ connections: [ [Object] ],
plugins: [],
models: ...
...
db:
...
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'myproject-dev',
options: { db: [Object], auth: {}, server: [Object], replset: [Object] },
otherDbs: [],
_readyState: 2,
_closeCalled: false,
知道有什么问题吗?
【问题讨论】:
标签: node.js mongodb mongoose npm