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
}
});
// 注册静态方法(statics) (实例方法用methods)
blogSchema.statics.findByTitle = function(mytitle,callback){
return this.find({title: mytitle},callback);
}
var Blog = mongoose.model('Blog', blogSchema); // 根据schema创建模型(类)
// 调用静态方法
Blog.findByTitle('博客标题',function(err,blog) {
console.log(blog);
});