【问题标题】:Mongoose - Referencing another model using requireMongoose - 使用 require 引用另一个模型
【发布时间】:2015-12-13 00:36:53
【问题描述】:

我要做的是更新一个收藏,奖品,然后根据更新另一个收藏的结果,联赛。

我有以下代码:

app.post('/auth/prize/:prizeId', function(req, res) {
    console.log('POST /auth/prize/' + req.params.prizeId);
    if (req.user) {
        var mess = 'JOINED';
        var query = {...};
        var update = {...};
        Prize.findOneAndUpdate(query, update, function(err, result) {
            if (err || result === null) {
                mess = 'ERROR Incorrect password';
                res.send(mess);
                return;
            }
            var League = require('./leagues_api');
            var queryL = {...};
            var updateL = {...};
            League.findOneAndUpdate(queryL, updateL, function(e, r) {
                if (e || r === null) {
                    mess = 'ERROR Incorrect password';
                }
                res.send(mess);
            });
        });
    } else {
        res.send(401, 'Not Admin!');
    }
});

所以,问题是我看到了一个错误:

[TypeError: Object #<Object> has no method 'findOneAndUpdate']

我有两个单独的文件来保持一切易于管理,所以我有这个文件,prizes_api.js,和另一个文件,leages_api.js,它在联赛的模式和模型中定义了它:

var leagueSchema = new mongoose.Schema({...});
var League = mongoose.model('League', leagueSchema);

我在其他地方使用了相同的样式,但由于某种原因,在这个文件中我看到了错误失败。请问这方面有什么建议吗?

谢谢你,加里。

【问题讨论】:

  • 谢谢,我知道我遗漏了一些简单的东西...(您可以重新发布作为答案,以便我接受)。我添加到leagues_api exports = module.exports = League; 让它工作

标签: javascript node.js mongodb mongoose mean-stack


【解决方案1】:

如果调用require('./leagues_api') 没有返回League 模型,那么您的module.exports 没有在该文件中正确设置。

它应该如下所示:

module.exports = League;

【讨论】:

  • 谢谢,忘记添加这部分了。对于我的设置,我添加:exports = module.exports = League; 到leagues_api.js 的底部(在最后的} 之前)。
  • 很高兴它有帮助。您不需要 exports = 部分。详情请见here
  • 是的,谢谢,将更新我的其他代码以反映这一点。
猜你喜欢
  • 2013-08-02
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 2022-01-21
  • 1970-01-01
  • 2021-07-31
相关资源
最近更新 更多