2017-10-02 5 views
0

私はどこにmongooseカスタム接続を定義するのか分かりません。私は現在、server.jsファイルに設定していますが、ドキュメンテーションを見ると、モデルへの接続を作成するために接続オブジェクトを使用しているため、モデルファイル自体の中に定義されているようです。mongooseカスタム接続の使用

// DOCの

var connection = mongoose.createConnection('mongodb://localhost:27017/test'); 
var Tank = connection.model('Tank', yourSchema); 

から、私が持っている問題は、私は、サーバーのファイルで作成された接続を持っているので、それはconnectionが何であるかを知らないんです。あなたのserver.js

//Server.js

var databaseUri = "mongodb://localhost/food"; 

if (process.env.MONGODB_URI) { 
    mongoose.createConnection(process.env.MONGODB_URI); 
} else { 
    mongoose.createConnection(databaseUri) 
} 

var database = mongoose.connection; 

database.on("error", function(err) { 
    console.log("Mongoose Error: ", err); 
}); 

database.once("open", function() { 
    console.log("Mongoose connection successful."); 
}); 

マイモデル

var mongoose = require("mongoose"); 

var Schema = mongoose.Schema; 

var UserSchema = new Schema({ 
    first_name: { 
    type: String, 
    trim: true, 
    required: "First Name is Required" 
    }, 
    last_name: { 
    type: String, 
    trim: true, 
    required: "Last Name is Required" 
    }, 
    email: { 
    type: String, 
    trim: true, 
    required: "Email is Required" 
    } 
}); 

//I need to use the connection I made in server js here, but not sure how. I tried exporting it from server file but it is not working. 
var User = mongoose.model("User", UserSchema); 

module.exports = User; 

答えて

0

、あなたがされるUserを要求する必要があります:

//connecton to the location of the database you use 
let databaseUri = "mongodb://localhost/food"; //you didn't include your port number. I try it on "mongodb://localhost:3000/food" 
let user = require('User'); //NOTE: ensure you reference the location of the `User` file correctly 

let port = process.env.PORT || 3000; 
let ip = process.env.IP || '127.0.0.1'; 

console.log("server started at http//:" + ip + ":" + port); 

これはあなたのモデルにあるはずです

let mongoose = require("mongoose"); 

//variable that will hold my connection 
let database = mongoose.connection; 
let mongoose = require('mongoose'); 

let Schema = mongoose.Schema; 


    // User Schema 
    let UserSchema = new Schema({ 
    first_name: { 
      type: String 
     },var UserSchema = new Schema({ 
    first_name: { 
    type: String, 
    trim: true, 
    required: "First Name is Required" 
    }, 
    last_name: { 
    type: String, 
    trim: true, 
    required: "Last Name is Required" 
    }, 
    email: { 
    type: String, 
    trim: true, 
    required: "Email is Required" 
    } 
}); 


//This line below exports the whole module to mongoose.model 
module.exports.User = mongoose.model('User', UserSchema); 
+0

ああ私はそこに接続を確立します。 – henhen

+0

接続を言うと、 'localhost:27017/test'のような意味ですか? – antzshrek

+0

いいえ私は自分のドキュメントにあるものをやっているのですが、代わりにサーバーファイルに入れています。ユーザをインポートした後、私は 'User = connection.model( 'User'、yourSchema);のようなことを考えていましたが、サーバファイル – henhen

関連する問題