在下面的代码中,obj在findOne回调中接收null。不明白为什么。在我的数据库中它看起来像这样。
MongoDB shell version: 2.2.0
connecting to: test
> use test
switched to db test
> db.Restaurant.findOne();
{
"_id" : ObjectId("53372f9714b4d69cbfa2bbaf"),
"name" : "Printz",
"visit" : "2014-04-02 19:00:00"
}
代码app.js
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var moment = require('moment');
var mongoose = require('mongoose');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var connection = mongoose.connection;
connection.on('error', console.error);
connection.once('open', function() {
console.log("open!");
});
console.log("Open database")
mongoose.connect('mongodb://localhost/test');
var eventSchema = new mongoose.Schema({
name: String,
visit: Date
});
var Restaurant = mongoose.model('Restaurant', eventSchema);
app.get('/', function(req, res) {
Restaurant.findOne({}, function(err, obj) {
if (err || !obj) {
res.send(500);
console.log("error: " + err + ", obj: " + obj);
return;
}
console.log("obj: " + obj);
res.render('index', {
name: obj.name
});
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
答案 0 :(得分:7)
另一个猫鼬自动复数集合名称的受害者。 Mongoose正在查询该集合' Restaurants'而不是'餐厅'。
var eventSchema = new mongoose.Schema({
name: String,
visit: Date
}, {collection: 'Restaurant'}); //override default collection name
var Restaurant = mongoose.model('Restaurant', eventSchema);
有关详细信息,请参阅the docs on mongoose.Model and util.toCollectionName。