简体   繁体   English

插入猫鼬集合并导出模型

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

I'm having trouble understanding mongoose and exporting in node/express. 我在理解猫鼬和在节点/表达式中导出时遇到了麻烦。

I have this model.js file 我有这个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;

And I want to export this var User so that I can use it later to insert new users in my app.post routes in my app.js. 而且我想导出此var User,以便以后可以使用它在app.js的app.post路由中插入新用户。

var User = require("User")

But it says the module User is undefinded or something similar. 但是它说模块User是未定义的或类似的东西。

As long as your model.js file is required before you intend to use the model you can use Mongoose's internal model cache to retrieve a model in any other file. 只要您打算使用model之前需要model.js文件,就可以使用Mongoose的内部模型缓存在任何其他文件中检索模型。

main_file.js 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

Sidenote: count is an async operation so your conditional check is not working as you intended. 旁注: count是一个异步操作,因此您的条件检查无法按预期进行。

I am assuming model.js is the name of your file. 我假设model.js是文件的名称。

You need to include the path to the model.js. 您需要包括到model.js的路径。 For example, if I had model.js in a folder called models in my projects root directory, then I would do this: 例如,如果在我的项目根目录中的模型文件夹中有model.js,则可以这样做:

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

When you use require() npm assumes you are either talking about one of the core modules or one of the npmjs packages in the ./node_modules directory. 当您使用require()时,npm假设您正在谈论./node_modules目录中的核心模块之一或npmjs软件包之一。 If it is not a core module or located in node_modules, then node won't know where to find it--unless you give it the full path. 如果它不是核心模块或不在node_modules中,则节点将不知道在哪里找到它-除非您提供完整路径。 This blog post explains it nicely: 这篇博客文章很好地解释了它:

http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm 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