简体   繁体   English

为什么我的 Mongoose findAll 方法返回 500 错误..?

[英]Why is my Mongoose findAll method returning a 500 error ..?

Here is my model / Schema.这是我的模型/架构。 The create method works, but the "all" method will not.. It returns a 500.. 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);

Here is my controller:这是我的控制器:

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

Routes:路线:

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

The create method works fine, but when I hit the get endpoint, with the index / all method -- I keep getting a 500. create 方法工作正常,但是当我使用 index / all 方法到达 get 端点时 - 我一直得到 500。

I can put the query directly in the controller, and it works.我可以将查询直接放在控制器中,它可以工作。

But, when I try to invoke it from the schema method -- it won't.但是,当我尝试从模式方法调用它时 - 它不会。

Am I using the methods wrong?我使用的方法有误吗? Is my JS off?我的JS关闭了吗?


Update:更新:

if I put this code in the controller, it works:如果我将此代码放在控制器中,它会起作用:

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

Still interested in the original question of "why the method is not working from the model".仍然对“为什么该方法不能从模型中工作”的原始问题感兴趣。


i've also tried this refactor in the model, to no avail:我也在模型中尝试过这种重构,但无济于事:

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

& &

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

Okay, so a few things..好吧,有几件事..

The model needed to be changed to a static method.该模型需要更改为静态方法。 A method of the model.模型的一种方法。

Also, the syntax needed to be changed.此外,需要更改语法。

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

If anyone would like to give a better description in layman's as to why these two changes were needed -- i'll be happy to change ownership of the correct answer.如果有人想用外行人更好地描述为什么需要这两个更改 - 我很乐意更改正确答案的所有权。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM