解决了一些问题后,一切似乎都正常,但页面不显示来自 MongoDB 的数据。看起来它正在尝试连接,但最终总是失败。
我什至将我的 Mongo 集合放到 mLab 上,看看它是否可以连接到本地主机以外的其他地方。事实并非如此。
我有一个 Server.js 文件
// modules =================================================
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
// config files
var port = process.env.PORT || 8080; // set our port
var db = require('./config/db');
// connect to our mongoDB database (commented out after you enter in your own credentials)
connectionsubject = mongoose.createConnection(db.urlSubjectViews);
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
// routes ==================================================
require('./app/routes')(app); // pass our application into our routes
// start app ===============================================
app.listen(port);
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
用于指向数据库的 db.js 文件:
module.exports = {
urlSubjectViews: 'mongodb://localhost:27017/donorschoose',
}
一个SubjectViews.js文件来指向我需要的数据
// define our nerd model
// module.exports allows us to pass this to other files when it is called
module.exports = connectionsubject.model('', {}, 'projects');
还有一个 Route.js 文件,用于为 JSON 数据设置路由
var Subjects = require('./models/SubjectViews');
module.exports = function(app) {
// server routes ===========================================================
// handle things like api calls
// authentication routes
// sample api route
app.get('/api/data', function(req, res) {
// use mongoose to get all nerds in the database
Subjects.find({}, {'_id': 0, 'school_state': 1, 'resource_type': 1, 'poverty_level': 1, 'date_posted': 1, 'total_donations': 1, 'funding_status': 1, 'grade_level': 1}, function(err, subjectDetails) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(subjectDetails); // return all nerds in JSON format
});
});
// frontend routes =========================================================
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
}
这是我在 Studio 3T 中的收藏: Mongo Collection
我知道它指向数据库,因为当我查看 localhost:8080/api/data 时,页面显示正在加载,但一段时间后超时。看来只有我有这个问题?
最佳答案
在这种情况下,更普遍的问题是,您正在遵循一个已有 3 年历史的教程,该教程基于一个不能像广告中那样工作的软件包(至少不再或不适合我)。
opc: git clone https://github.com/anmolkoul/node-dc-mongo.git
Cloning into 'node-dc-mongo'...
remote: Counting objects: 930, done.
remote: Total 930 (delta 0), reused 0 (delta 0), pack-reused 930
Receiving objects: 100% (930/930), 1.75 MiB | 0 bytes/s, done.
Resolving deltas: 100% (133/133), done.
opc: cd node-dc-mongo/
node-dc-mongo>: rm -rf node_modules/
node-dc-mongo>: npm install
npm WARN deprecated mongodb@1.4.38: Please upgrade to 2.2.19 or higher
> bson@0.2.22 install /Users/lineus/dev/opc/node-dc-mongo/node_modules/bson
> (node-gyp rebuild 2> builderror.log) || (exit 0)
CXX(target) Release/obj.target/bson/ext/bson.o
> kerberos@0.0.11 install /Users/lineus/dev/opc/node-dc-mongo/node_modules/kerberos
> (node-gyp rebuild 2> builderror.log) || (exit 0)
CXX(target) Release/obj.target/kerberos/lib/kerberos.o
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN starter-node-angular@1.0.1 No repository field.
npm WARN starter-node-angular@1.0.1 No license field.
added 64 packages in 8.994s
node-dc-mongo>: node server.js
{ Error: Cannot find module '../build/Release/bson'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/lineus/dev/opc/node-dc-mongo/node_modules/bson/ext/index.js:15:10)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3) code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Magic happens on port 8080
^C
node-dc-mongo>:
因此,需要做一些工作才能使其顺利进行。
让我们首先通过创建一个模仿代码 Mongoose 部分的独立文件来稍微简化问题空间,以便更容易推理。 (我使用的是较新版本的 Mongoose,但详细信息是相同的)。
'use strict'
const mongoose = require('mongoose')
const conn = mongoose.createConnection('mongodb://localhost/test')
const Model = conn.model('', {}, 'tests')
Model.find({}, (err, docs) => {
if (err) { return console.error(err) }
console.log(`there are ${docs.length} docs in this collection.`)
return conn.close()
})
如果我们运行此代码,则没有输出,并且一切都显得卡住。
49715319: node ./connect.js
^C
49715319:
createConnection方法返回一个继承自eventEmitter的连接对象。为了成功使用返回的连接对象,我们必须“监听”“打开”事件。
我们可以像这样更改我们的文件:
'use strict'
const mongoose = require('mongoose')
const conn = mongoose.createConnection('mongodb://localhost:27017/test')
const Model = conn.model('', {}, 'tests')
conn.on('open', function (err) {
if (err) { return console.error(err) }
Model.find({}, (err, docs) => {
if (err) { return console.error(err) }
console.log(`there are ${docs.length} docs in this collection.`)
return conn.close()
})
})
输出变为:
49715319: node ./connect.js
there are 1000 docs in this collection.
49715319:
这意味着您应该像这样更改 server.js 文件:
// modules =================================================
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
// config files
var port = process.env.PORT || 8080; // set our port
var db = require('./config/db');
// connect to our mongoDB database (commented out after you enter in your own credentials)
connectionsubject = mongoose.createConnection(db.urlSubjectViews);
connectionsubject.on('open', function (err) {
if (err) { return console.error(err) }
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
// routes ==================================================
require('./app/routes')(app); // pass our application into our routes
// start app ===============================================
app.listen(port);
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
})
在 Mongoose 成功连接到服务器之前,这不会启动 Express 应用程序。
考虑到您使用的 Mongoose 版本,它可能仍然无法工作。如果仍然失败,我建议安装最新版本的 Mongoose 或至少在撰写本文时安装最新版本的 Mongoose 4。
为了完整起见,这就是我为这个测试集合生成文档的方式(使用 Mongoose 5 ):
#!/usr/bin/env node
'use strict'
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')
const Schema = mongoose.Schema
const schema = new Schema({
name: String
})
const Test = mongoose.model('test', schema)
const tests = []
for (let i = 0; i < 1000; i++) {
tests.push(new Test({ name: `testing${i}` }))
}
async function run () {
await mongoose.connection.dropDatabase()
let docs = await Test.create(tests)
console.log(`added ${docs.length} docs to ${Test.modelName}`)
return mongoose.connection.close()
}
run()
关于javascript - 如何调试不会从 MongoDB 检索数据的 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49715319/