• node--20 moogose demo2


    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},
        sex      :  {type : String}
    });
    //创建静态查找方法
    studentSchema.statics.zhaoren = function(name, callback) {
        this.model('Student').find({name: name}, callback);
    };
    //创建修改的静态方法
    studentSchema.statics.xiugai = function(conditions,update,options,callback){
        this.model("Student").update(conditions, update, options, callback);
    }
    //创建了一个模型,就是学生模型,就是学生类。
    //类是基于schema创建的。
    var studentModel = db.model('Student', studentSchema);
    //向外暴露
    module.exports = studentModel;

    app.js

    /**
     * Created by Danny on 2015/9/28 16:45.
     */
    
    //定义了一个模型,学生模型,“学生类”
    var Student = require("./models/Student.js");
    ////实例化了一个学生类
    //var xiaoming = new Student({"name":"小明","age":12,"sex":"男"});
    ////保存这个学生类
    //xiaoming.save(function(){
    //    console.log("存储成功");
    //});
    
    //用类来创建一个对象(工厂)
    Student.create({"name":"小红","age":13,"sex":"女"},function(error){
       console.log("保存成功");
    })
    //
    Student.zhaoren("小明",function(err,result){
        console.log(result);
    });
    
    Student.xiugai({"name":"小明"},{$set : {"age":30}},{},function(){
        console.log("改年龄成功");
    });
  • 相关阅读:
    With great power comes great responsibility
    2016年你应该学习的语言和框架
    箜篌长萧各一曲,月清淡似风人未眠。
    使用 RUP 管理小型项目和团队
    php文件加锁 lock_sh ,lock_ex
    PHP_EOL
    PHP输入流php://input介绍
    获取ip地址
    关键词拍卖和广义二阶拍卖(Internet Advertising and the Generalized Second-Price Auction译文)
    常用js选择
  • 原文地址:https://www.cnblogs.com/yaowen/p/7047054.html
Copyright © 2020-2023  润新知