Node.js 使用mongoose自定义连接
我不确定在哪里定义mongoose自定义连接。我目前在server.js文件中设置了它,但在查看文档时,它似乎是在模型文件本身中定义的,因为他们在创建到模型的连接后使用了connection对象 //从医生那里Node.js 使用mongoose自定义连接,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我不确定在哪里定义mongoose自定义连接。我目前在server.js文件中设置了它,但在查看文档时,它似乎是在模型文件本身中定义的,因为他们在创建到模型的连接后使用了connection对象 //从医生那里 var connection = mongoose.createConnection('mongodb://localhost:27017/test'); var Tank = connection.model('Tank', yourSchema); 我遇到的问题是,由于我在服务器文
var connection = mongoose.createConnection('mongodb://localhost:27017/test');
var Tank = connection.model('Tank', yourSchema);
我遇到的问题是,由于我在服务器文件中建立了连接,它不知道什么是连接
//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;
在您的server.js中,您需要
用户
,该用户将:
//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);
啊,我明白了,然后在那里建立连接。当你说连接时,你的意思是像
localhost:27017/test
一样吗?不,我的意思是做他们文档中的事情,而是把它放在我的服务器文件中。导入用户后,我想做一些类似于User=connection.model('User',yourSchema)的事情代码>但在服务器文件中,我认为这实际上不起作用,因为我的模型中有这个,并将其导出到那里,我认为在我的服务器中有这个并从那里导出它是没有意义的,除非这是正确的方法。我试图使用mongoose的createConnection(),而不是常规连接()。另外,在模型中创建连接本身不是一个很好的地方吗?