使用mongoose自定义连接

时间:2017-10-02 20:42:28

标签: node.js mongodb mongoose

我不确定在哪里定义mongoose自定义连接。我目前在我的server.js文件中设置了它,但是在查看文档时,似乎它是在模型文件本身内部定义的,因为它们之后使用连接对象来创建与模型的连接。

//来自DOC&#39>

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

我遇到的问题是因为我在服务器文件中建立了连接,所以它不知道connection是什么。

// 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;

1 个答案:

答案 0 :(得分:-1)

server.js 中,您需要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);