1.创建数据库连接模块 conn_mongo.js
/** * 连接MongoDB数据库 */ var mongoose=require("mongoose"); mongoose.connect("mongodb://127.0.0.1/mongoose_test",{useMongoClient:true}); mongoose.connection.once("open",function(){ console.log("数据库连接成功~"); });
2.创建集合的模型 student.js
/** * 用来定义Student的模型 */ var mongoose =require("mongoose"); var Schema=mongoose.Schema; var stuSchema=new Schema({ name:String, age:Number, gender:{//数据类型是String,默认值是 female type:String, default:"female" }, address:String }); //定义模型 var StuModel=mongoose.model("students",stuSchema); //导出 module.exports=StuModel;
3.创建测试模块 index.js
//引入conn_mongo模块连接数据库 require("./conn_mongo"); var Student=require("./models/student"); Student.find({},function(err,docs){ if(!err){ console.log(docs); } });