繁体   English   中英

插入猫鼬集合并导出模型

[英]Inserting into a mongoose collection and exporting the model

我在理解猫鼬和在节点/表达式中导出时遇到了麻烦。

我有这个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")

但是它说模块User是未定义的或类似的东西。

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

main_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是一个异步操作,因此您的条件检查无法按预期进行。

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

您需要包括到model.js的路径。 例如,如果在我的项目根目录中的模型文件夹中有model.js,则可以这样做:

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

当您使用require()时,npm假设您正在谈论./node_modules目录中的核心模块之一或npmjs软件包之一。 如果它不是核心模块或不在node_modules中,则节点将不知道在哪里找到它-除非您提供完整路径。 这篇博客文章很好地解释了它:

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

暂无
暂无

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

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