db.js
/** * Created by Danny on 2015/9/28 16:44. */ //引包 var mongoose = require(‘mongoose‘); //创建数据库连接,每一个用户都会创建一个db, var db = mongoose.createConnection(‘mongodb://127.0.0.1:27017/haha‘); //监听open事件 db.once(‘open‘, function (callback) { console.log("数据库成功连接"); }); //向外暴露这个db对象 module.exports = db;
Students.js
/** * Created by Danny on 2015/9/28 16:47. */ var mongoose = require(‘mongoose‘); var db = require("./db.js"); //创建了一个schema结构。 var studentSchema = new mongoose.Schema({ name : {type : String}, age : {type : Number}, }); var studentModel = db.model(‘Student‘,studentSchema);//通过db定义一个类,类名和属性 module.exports = studentModel;//外部var Student = require("./models/Student.js");此时Student = studentModel;
app.js
var Student = require("./models/Student.js"); //第一种创建方式 var xiaoming = new Student({"name":"小明","age":12}); xiaoming.save(function(){//save是对象的方法 console.log("存储成功"); }); //第二种创建方式 Student.create({"name":"小红","age":13,"sex":"女"},function(error){ console.log("保存成功"); })
时间: 2024-12-18 23:10:24