来自星星的码农 - 个人博客

来自星星的码农 - 个人博客

在Node.js中操作MongoDB数据库,你可以使用几种不同的库,最流行的是mongodb和mongoose。这里介绍一下mongoose的使用

引入数据库模块

const mongoose = require('mongoose');

数据库连接

//监听http请求 连接MongoDB
mongoose.connect('mongodb://localhost:27017/demo', function(err) {
    if (err) {
        console.log('数据库连接失败');
    } else {
        console.log('数据库连接成功');
        server.listen(8080);
    }
});

Schema简介

Schema:一种以文件形式存储的数据库模型骨架,无法直接通往数据库端,也就是说它不具备对数据库的操作能力,仅仅只是数据库模型在程序片段中的一种表现,可以说是数据属性模型(传统意义的表结构),又或着是"集合"的模型骨架。

//var schema = new mongoose.Schema(模型骨架)
var schema = new mongoose.Schema({ 
	title: {
        type: String,
        default: ''
    },
	newsType: {
        type: Number,
        default: 0
    },
	comments: {
        type: Array,
        default: []
    },
    isAdmin: {
        type: Boolean,
        default: false
    }, 
	time: {
        type: Date,
        default: ''
    }
});

创建Model

var Model = db.model("表名", schema,"表名"); // 第三个参数不加的话数据库表名会自动加's'

操作数据库

var News = require('../models/newsModel'); // 新闻模型

// 增一 ----- var model = new Model(增加数据);  model.save(callback);
var news = new News({ title: 'hehe' });
news.save(function (err) {
	if (err) return handleError(err);
	res.send("插入数据成功").end();
})
// 增二 -----  Model.create(增加的数据, callback))
News.create({ title:"create", intro:"cr"}, function(error,doc){
	 if(error) {
	  	console.log(error);
	 } else {
	    console.log('create',doc);
	 }
});


// 删 -----  Model.remove(查询条件,callback);
var conditions = { "_id" : '5af255d7558b072398606fac' };
News.remove(conditions, function(error){
    if(error) {
	   console.log(error);
	} else {
	   console.log('删除成功!');
	}
});


// 改 -----  Model.update(查询条件,更新对象,callback);
var conditions = {"title" : "a"};
var update = {$set : { "intro" : "369","content" : "987" }};
News.update(conditions, update, function(error){
	 if(error) {
	   console.log(error);
	 } else {
	   console.log('修改成功!');
	 }
});


// 查 -----  Model.find(查询条件,callback);
News.find({"title": "123","content":"666"},function(error,docs){ //若没有向find传递参数,默认的是显示所有数据
	 console.log(docs);
});



增删改查小结

  • 查询:find查询返回符合条件一个、多个或者空数组文档结果。

  • 保存:model调用create方法,entity调用的save方法。

  • 更新:obj.update(查询条件,更新对象,callback),根据条件更新相关数据。

  • 删除:obj.remove(查询条件,callback),根据条件删除相关数据。

find过滤查询

属性过滤 find(Conditions,field,callback);

  • Conditions:查询条件
  • field:过滤条件
  • callback:查询回调函数
/**
 *  我们只需把要显示的属性设置为大于零的数就可以,比如1,_id是默认返回,如果不要显示加上("_id":0),
 *  但是,对其他不需要显示的属性且不是_id,如果设置为0的话将会抛异常或查询无果
 *
**/

News.find({"title": "123"},{title:1, content:1, _id:0},function(error,docs){ //若没有向find传递参数,默认的是显示所有数据
	  console.log(docs); // 只返回title和content两字段
});
  • find过滤查询 :find查询时我们可以过滤返回结果所显示的属性个数。

  • findOne查询 :只返回符合条件的首条文档数据。

  • findById查询:根据文档_id来查询文档。

数据库高级查询

大于、小于 : $gt(>)、$lt(<)、$lte(<=)、$gte(>=)

 Model.find({"age":{"$gt":18}},function(error,docs){
    //查询所有age大于18的数据
 });

不等于: $ne(!=)

Model.find({age:{ $ne:24}},function(error,docs){
    //查询age不等于24的所有数据
});

匹配: $in 包含、等于

Model.find({ age:{ $in: 20}},function(error,docs){
  //查询age等于20的所有数据
});

Model.find({ age:{$in:[20,30]}},function(error,docs){
  //可以把多个值组织成一个数组
});

或者 $or

Model.find({"$or":[{"name":"hehe"},{"age":18}]},function(error,docs){
    //查询name为hehe或age为18的全部文档
});

存在 $exists

 Model.find({name: {$exists: true}},function(error,docs){
    //查询所有存在name属性的文档
 });

 Model.find({telephone: {$exists: false}},function(error,docs){
    //查询所有不存在telephone属性的文档
 });