【发布时间】: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