【问题标题】:Node.js + Mongoose - what's going wrong?Node.js + Mongoose - 出了什么问题?
【发布时间】:2013-05-19 02:35:41
【问题描述】:

我一直在研究一个 node.js + mongoose 简单的应用程序,但是,出了点问题。我一直在根据这个网站的一些例子工作,但一点也不幸运。 代码运行,但是,没有从 db (已填充,顺便说一句)返回任何记录。有人可以看看并给我一些帮助吗?我已经为此工作了一天多,但没有任何乐趣。

models/entidade.js

var mongoose = require('mongoose')
   ,Schema = mongoose.Schema
   ,ObjectId = Schema.ObjectId;

var entidadeSchema = new Schema({
        cnpj:  String,
        razaoSocial: String,
        nomeFantasia:   String,
        endereco: String,
        unidades: [{ codigo: String, nome: String, endereco: String, ativo: {type: Boolean, default: true} }],
        dataCriacao: { type: Date, default: Date.now },
        cadastroAtivo: { type: Boolean, default: false },
    });

module.exports = mongoose.model('Entidade', entidadeSchema);

routes/entidades.js

var Entidade = require('../models/entidade.js');

exports.list = function(req, res) {
    Entidade.find(function(err, entidades) {
        console.log("route IN: %d records", entidades.length );
        res.send(entidades);
    });
};

最后,server.js

var express = require('express');     
var app = express();

app.configure(function () {
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
});

// connection to mongoDB
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/ccidev');    

var entidade = require('./routes/entidades');

app.get('/entidades/list', entidade.list);

app.listen(3000);

正如我所说,在运行应用程序时,我没有收到任何错误,而是一个空的结果。任何帮助表示赞赏。

感谢和问候, 维尼修斯

【问题讨论】:

    标签: node.js mongodb rest express mongoose


    【解决方案1】:

    根据documentation,Model.find()的第一个参数是条件 试试看

    Entidade.find({}, function(err, entidades) {});
    

    routes/entidades.js

    var Entidade = require('../models/entidade.js');
    
    exports.list = function(req, res) {
        Entidade.find({}, function(err, entidades) {
            console.log("route IN: %d records", entidades.length );
            res.send(entidades);
        });
    };
    

    【讨论】:

    • 起初我也是这么想的,但find() 似乎工作得很好,没有任何条件通过(而且只是一个回调)。顺便说一句,您的答案也缺少条件......
    • 是的,伙计们,find() 应该可以正常工作。我发现了问题...数据库是在应用程序之外创建的。我的意思是,我没有使用该应用程序加载数据。所以我尝试使用 POST 方法加载相同的数据,它工作正常。现在正在显示数据(与以前的模式的唯一区别是 __v 属性,该属性已由 mongoose 添加用于版本控制)。很奇怪,但至少,现在可以了!非常感谢@lemulot 和@robertklep 的想法!我非常感谢您的反馈! :)
    猜你喜欢
    • 2021-06-19
    • 2015-02-26
    • 2015-02-19
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2013-11-16
    相关资源
    最近更新 更多