【问题标题】:Inserting into a mongoose collection and exporting the model插入猫鼬集合并导出模型
【发布时间】:2015-04-29 02:51:11
【问题描述】:

我在理解 mongoose 和在 node/express 中导出时遇到问题。

我有这个 model.js 文件

var mongoose = require("mongoose"),
  Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String
});

var User = mongoose.model("User", UserSchema);

if (User.count() == 0) {
    User.insert({name: 'john doe'})
};

module.exports = User;

我想导出这个 var User 以便以后可以使用它在我的 app.js 中的 app.post 路由中插入新用户。

var User = require("User")

但它说模块用户未定义或类似的东西。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    只要在您打算使用模型之前需要您的 model.js 文件,您就可以使用 Mongoose 的内部模型缓存来检索任何其他文件中的模型。

    ma​​in_file.js

    var mongoose = require('mongoose');
    require('./model.js') // loads models
    // Only need to load them once for entire project
    
    var User = mongoose.model('User'); // Notice no schema provided
    // You can do this in any other file as long as
    // they are required after the models are loaded
    

    旁注:count 是异步操作,因此您的条件检查无法按预期工作。

    【讨论】:

    • 那么如何检查集合是否为空并制作新文档?
    • 阅读答案中链接的文档:提供回调。比如:User.find().count(callback)
    【解决方案2】:

    我假设 model.js 是你的文件名。

    您需要包含 model.js 的路径。例如,如果我的项目根目录中名为 models 的文件夹中有 model.js,那么我会这样做:

    var User = require("./models/model")
    

    当您使用 require() 时,npm 假定您正在谈论核心模块之一或 ./node_modules 目录中的 npmjs 包之一。如果它不是核心模块或位于 node_modules 中,那么 node 将不知道在哪里可以找到它——除非你给它完整的路径。这篇博文很好地解释了这一点:

    http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2014-07-15
      • 2015-06-12
      • 2012-07-21
      • 2016-07-03
      相关资源
      最近更新 更多