1.链接优化
1.1.创建tools文件夹,并创建conn_mongo文件
/*
定义一个模块,用来链接MongoDB数据库
*/
var mongoose = require("mongoose");
mongoose.connect("mongo://127.0.0.1/mongoose_test",{useMongoClient:true});
mongoose.connect.once("open",function(){
console.log("数据库连接成功~~~")
});
2.model优化
2.1.创建models文件夹,并创建student文件
/*
用来定义Student的模型
*/
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var stuSchema = new Schema({
name:String,
age:Number,
gender:{
type:String,
default:"female"
},
address:String
});
//定义模型
var StuModel = mongoose.model("student",stuSchema);
module.exports = StuModel;
3.对以上测试
/*
调用连接
*/
require("./tools/conn_mongo");
var Student = require("./models/student");
Student.find({},function(err,docs){
if(!err){
console.log(docs);
}
});