猫鼬findOne回调使我为空

猫鼬findOne回调使我为空

本文介绍了猫鼬findOne回调使我为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,obj在findOne回调中接收到null.不明白为什么.在我的数据库中,看起来像这样.

In the code below obj receives null in the findOne callback. Don't understand why. In my database it looks like this.

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'));
});

推荐答案

猫鼬自动复数集合名称的另一个受害者.猫鼬正在查询集合餐厅"而不是餐厅".

Yet another victim of mongoose auto-pluralization of collection names. Mongoose is querying the collection 'Restaurants' instead of 'Restaurant'.

var eventSchema = new mongoose.Schema({
  name: String,
  visit: Date
}, {collection: 'Restaurant'}); //override default collection name

var Restaurant = mongoose.model('Restaurant', eventSchema);

有关详细信息,请参见有关mongoose.Model和util.toCollectionName 的文档.

For details see the docs on mongoose.Model and util.toCollectionName.

这篇关于猫鼬findOne回调使我为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 03:04