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;
ああ私はそこに接続を確立します。 – henhen
接続を言うと、 'localhost:27017/test'のような意味ですか? – antzshrek
いいえ私は自分のドキュメントにあるものをやっているのですが、代わりにサーバーファイルに入れています。ユーザをインポートした後、私は 'User = connection.model( 'User'、yourSchema);のようなことを考えていましたが、サーバファイル – henhen