码迷,mamicode.com
首页 > 其他好文 > 详细

node--19 moogose demo1

时间:2017-06-19 10:02:58      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:str   string   module   code   pen   监听   mongod   ring   port   

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("保存成功");
})

 

node--19 moogose demo1

标签:str   string   module   code   pen   监听   mongod   ring   port   

原文地址:http://www.cnblogs.com/yaowen/p/7047053.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!