【问题标题】:Why is my Mongoose findAll method returning a 500 error ..?为什么我的 Mongoose findAll 方法返回 500 错误 ..?
【发布时间】:2016-08-30 17:23:48
【问题描述】:

这是我的模型/架构。 create 方法有效,但“all”方法无效。它返回 500 ..

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

var DiSchema = new mongoose.Schema({
  name: { type: String, lowercase: true , required: true },
  photo: { type: String },
  email: { type: String, unique: true, lowercase: true },
  year: { type: Number},
  timestamp: { type : Date, default: Date.now },
  description: { type: String},
  location: { type: Array },
  social: {
    website: {type: String},
    facebook: {type: String },
    twitter: {type: String },
    instagram: {type: String }
  }
});

DiSchema.methods.create = function(o, cb){
  this.model.save(o, cb);
};

DiSchema.methods.all = function(o, cb){
  Di.find(o, cb);
};

module.exports = mongoose.model('Di', DiSchema);

这是我的控制器:

'use strict';

var Di = require('../models/di');

exports.create = function(req, res){
  Di.create(req.body , function(err, di){
    console.log('req.body.di', req.body);
    res.send({di:di});
  });
};

exports.index = function(req, res){
  Di.all({}, function(err, dis){
    res.send({dis:dis});
  });
};

路线:

var dis = require('../contollers/dis');
app.get('/dis', dis.index);
app.post('/dis', dis.create);

create 方法工作正常,但是当我使用 index / all 方法到达 get 端点时——我一直得到 500。

我可以将查询直接放在控制器中,它可以工作。

但是,当我尝试从架构方法调用它时——它不会。

我是否使用了错误的方法?我的JS关了吗?


更新:

如果我把这段代码放在控制器中,它就可以工作:

exports.index = function(req, res){
  Di.find({}, function(err, dis) {
    if (!err){ 
        res.send(dis);
  };
});
};

仍然对“为什么该方法在模型中不起作用”的原始问题感兴趣。


我也在模型中尝试过这种重构,但无济于事:

DiSchema.methods.list = function(o, cb){
  this.model.find(o, cb);
};

&

DiSchema.methods.list = function(o, cb){
  this.model('Di').find(o, cb);
};

【问题讨论】:

  • 导致500错误的异常包含什么?你应该可以从那里调试它。
  • 我在检查器工具中没有在网络上显示任何内容。唯一显示 500 的是摩根——在终端。我会进一步研究调试这个。如果我将 console.log 放在 Distiller.all 函数中(在控制器内),它永远不会被击中,所以似乎该函数没有被正确调用或被挂起......

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

好的,有几件事..

需要将模型更改为静态方法。模型的一种方法。

此外,还需要更改语法。

DiSchema.statics.all = function(o, cb){
  this.model('Di').find(o, cb);
};

如果有人想以通俗易懂的方式更好地描述为什么需要这两项更改 - 我很乐意更改正确答案的所有权。

【讨论】:

    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2023-03-18
    • 1970-01-01
    • 2013-05-30
    相关资源
    最近更新 更多