簡體   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