Node.js mongoose操作mongoDB, 注册实例方法(methods)


demo.js:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;  // 获取数据库的连接对象。
db.once('open', function (callback) {
    console.log("数据库成功打开");
});

// Schema 博客的结构 (表结构)
var blogSchema = new mongoose.Schema({
    title:  String,
    author: String,
    body:   String,
    comments: [{ body: String, date: Date }],
    date: { type: Date, default: Date.now },
    hidden: Boolean,
    meta: {
        votes: Number,
        favs:  Number
    }
});

// 注册实例方法(methods)  (静态方法用statics)
blogSchema.methods.showInfo = function(){
    console.log(this.title); // this指向该实例(对象)
}

var Blog = mongoose.model('Blog', blogSchema);  // 根据schema创建模型(类)

// 第一种方式:创建实例
var blog = new Blog({
    "title" : "博客测试",
    "author" : "考拉"
});

// 第二种方式:创建实例 (直接保存到数据库)
Blog.create({
    "title" : "博客测试2",
    "author" : "考拉2"
});

//blog.save();  // 实例保存到数据库中。
blog.showInfo();  // 调用实例的方法。


demo2.js:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;
db.once('open', function (callback) {
    console.log("数据库成功打开");
});

// 结构
var animalSchema = new mongoose.Schema({
    "name" : String,
    "type" : String
});

// 注册实例方法(methods)  静态方法(statics)
animalSchema.methods.zhaotonglei = function(callback){
    this.model('Animal').find({"type":this.type},callback);  // this就指向该实例(对象)
}

var Animal = mongoose.model('Animal', animalSchema);

//Animal.create({"name":"汤姆","type":"猫"});  // 数据库中新增一些数据
//Animal.create({"name":"咪咪","type":"猫"});
//Animal.create({"name":"小白","type":"狗"});
//Animal.create({"name":"snoopy","type":"狗"});


// findOne就对应mongoDB中的shell操作命令。
Animal.findOne({"name":"小白"},function(err,result){
    var dog = result;  // 查找出来的结果就是一个实例(对象)
    dog.zhaotonglei(function(err,result){  // 调用实例方法
        console.log(result);
    });
});




猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/80381550
今日推荐