【问题标题】:Using a Mongoose model defined in another file returns Undefined使用在另一个文件中定义的 Mongoose 模型返回 Undefined
【发布时间】:2021-01-09 21:26:17
【问题描述】:

似乎很清楚,在一个文件中定义模型但在另一个文件中使用它是常见的做法。我不知道为什么我很难让它工作。我花了一个上午重写了我的简单 MongoDB 应用程序,以遵循我认为的 dead simple example。我只是将它构建为最重要的答案,增加了我定义架构和模型并访问模型的文件在同一个文件夹中的便利(因为项目太小而且我只是在学习 MongoDB)。我认为,当我尝试研究解决方案时,部分问题在于其他示例确实很难遵循。数据库按预期连接,我可以在ManageDB.js 文件中正常工作,但当然希望保持项目井井有条,即使在我的小规模下也是如此。 (上面目录中的 server.js 文件在此代码执行之前连接。)

我还可以尝试哪些其他方法来解决此 MongoDB 应用程序的问题?

// src/ManageDB.js

const mongoose = require('mongoose');

const devTweetRecordsModel = new mongoose.Schema({
    time: Date,
    text: String,
    source: String,
    positive: Number,
    negative: Number,
});
var tweetdb = mongoose.model('DevTweetDB', devTweetRecordsModel);

module.exports = {
    tweetdb: tweetdb
};


// src/TwitterAPI.js
    
const mongoose = require('mongoose');
var tweetdb = require('../src/ManageDB').tweetdb;

console.log(tweetdb); // Returns undefined

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    在 mongoose 中定义模型模式后,您应该将其指定为 mongoose.model 正如您在文档中看到的那样。

    https://mongoosejs.com/docs/models.html

    const schema = new mongoose.Schema({ name: 'string', size: 'string' });
    const Tank = mongoose.model('Tank', schema);

    当您在模式上调用 mongoose.model() 时,Mongoose 会为您编译模型。 然后你可以通过在另一个文件中要求它来使用它。

    const Model= require('./../models/modelName');

    【讨论】:

    • 即使这稍微短了一点,仔细检查我的示例是否符合您的建议仍然返回undefined
    【解决方案2】:

    我以从未在任何地方看到过建议的方式解决了这个问题,所以为了完整起见,我将在此处发布。该解决方案对我如何将其导出并带入其他 JS 文件的方式非常敏感。

    // Model.js
    module.exports = mongoose.model('DevTweetDB', devTweetRecordsModel);
    
    // TwitterAPI.js
    var tweetdb = require('../models/tweetdb');
    console.log(tweetdb);
    
    // Returns the object as expected:
    // Model { DevTweetDB }
    

    【讨论】:

      猜你喜欢
      • 2016-04-22
      • 2018-08-25
      • 2016-10-26
      • 2016-06-28
      • 2015-12-13
      • 2014-12-13
      • 2010-09-15
      • 2015-05-12
      • 2020-11-05
      相关资源
      最近更新 更多