mongodb操作之mongoose

2016/11/08 20:24
阅读数 5
/**
 * Created by chaozhou on 2015/10/6.
 */
var mongoose = require("mongoose");
var db = mongoose.createConnection("127.0.0.1", "cms");

//链接错误监听
db.on("error", function (error) {
    console.log(error);
});

//Schema结构
var userSchema = new mongoose.Schema({
    userName: {type: String, default: '匿名用户'},
    trueName: mongoose.Schema.Types.String,
    title: {type: String},
    content: {type: String},
    time: {type: Date, default: Date.now()},
    age: {type: Number}
});

//添加实例方法
userSchema.methods.findByUserName = function (userName, callBack) {
    return this.model("user").find({userName: userName}, callBack);
};

//添加静态方法,静态方法在model层就能使用
userSchema.statics.findByTitle = function (title, callBack) {
    return this.model("user").find({title: title}, callBack);
};

//model层
var userModel = db.model("user", userSchema);

//entity层
var doc = {userName: 'entity_demo_username', title: 'entity_demo_title', content: 'entity_demo_content'};
var userEntity = new userModel(doc);
//添加记录,基于entity的操作方式
userEntity.save(function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log("saved ok");
    }
});

//增加记录,基于model的操作方式
var doc2 = {username: 'model_demo_username', title: 'model_demo_title', content: 'model_demo_content'};
userModel.create(doc2, function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log("saved ok");
    }
    db.close(); //关闭数据库链接
});

//修改记录,args:conditions, update, options, callback
userModel.update({userName: 'model_demo_username'}, {
    $set: {
        age: 27,
        title: 'model_demo_title_update'
    }
}, {upsert: false}, function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log("update ok");
    }
    db.close();
});

//查询,基于实例方法的查询
userEntity.findByUserName('model_demo_username', function (err, result) {
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
    db.close();
});

//查询,基于静态方法的查询
userModel.findByTitle('model_demo_title', function (err, result) {
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
    db.close();
});

//查询,args:criteria, fields, options, callBack
userModel.find({title: 'entity_demo_title'}, {title: 1, content: 1, time: 1}, function (err, result) {
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
    db.close();
});

//删除记录
userModel.remove({userName: 'entity_demo_username'}, function (err, result) {
    if (err) {
        console.log(err);
    } else {
        console.log('delete ok');
    }
    db.close();
});

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部