Nodejs中使用Mongoose操作MongoDB数据库

Mongoose是在node.js异步环境下对mongodb进行便捷操作的对象模型工具。

直接使用docker部署一个MongoDB数据库。之后开始使用node来操作。

mongoose安装:全局 npm install mongoose -g 或者在目录中 安装到当前项目。

基本使用:

连接MongoDB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var mongoose = require('mongoose'),
DB_URL = 'mongodb://localhost:27017/nodetest';

/**
* 连接
*/
mongoose.connect(DB_URL);

/**
* 连接成功
*/
mongoose.connection.on('connected', function () {
console.log('Mongoose connection open to ' + DB_URL);
});

/**
* 连接异常
*/
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});

/**
* 连接断开
*/
mongoose.connection.on('disconnected', function () {
console.log('Mongoose connection disconnected');
});


module.exports = mongoose;
基本操作
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 用户信息
*/
var mongoose = require('../public/javascripts/mongodb.js');
var Schema = mongoose.Schema;

var User = new Schema({
username : { type: String }, //用户账号
pwd: {type: String}, //密码
age: {type: Number}, //年龄
logindate : { type: Date} //最近登录时间
});
module.exports = mongoose.model('User',User);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
var User = require("./user.js");

function insert() {
var user = new User({
username : 'hu', //用户账号
pwd: '123456', //密码
age: 20, //年龄
logindate : new Date() //最近登录时间
});

user.save(function (err, res) {
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
});
}

function update(username,pwd){
var wherestr = {'username' : username};
var updatestr = {'pwd': pwd};

User.update(wherestr, updatestr, function(err, res){
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})
}

function del(username){
var wherestr = {'username' : username};

User.remove(wherestr, function(err, res){
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})
}

//根据id修改
function findByIdAndUpdate(id,pwd){
var updatestr = {'pwd': pwd};

User.findByIdAndUpdate(id, updatestr, function(err, res){
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})
}
//条件查询
function getByConditions(username){
var wherestr = {'username' : username};

/*User.find(wherestr, function(err, res){
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})*/
//选择需要查询的字段,1表示查询输出该字段,0表示不输出
var opt = {"username": 1 ,"_id": 0};
User.find(wherestr,opt, function(err, res){
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})
}

/*
//这表示查询年龄大于等21而且小于等于65岁
ser.find({age: {$gte: 21, $lte: 65}}, callback);

其实类似的还有: 
  $or    或关系
  $nor    或关系取反
  $gt    大于
  $gte    大于等于
  $lt     小于
  $lte    小于等于
  $ne 不等于
  $in 在多个值范围内
  $nin 不在多个值范围内
  $all 匹配数组中多个值
  $regex  正则,用于模糊查询
  $size   匹配数组大小
  $maxDistance  范围查询,距离(基于LBS)
  $mod   取模运算
  $near   邻域查询,查询附近的位置(基于LBS)
  $exists   字段是否存在
  $elemMatch  匹配内数组内的元素
  $within  范围查询(基于LBS)
  $box    范围查询,矩形范围(基于LBS)
  $center 范围醒询,圆形范围(基于LBS)
  $centerSphere  范围查询,球形范围(基于LBS)
  $slice    查询字段集合中的元素(比如从第几个之后,第N到第M个元素)
*/
//数量查询
function getCountUsers(){
var wherestr = {};

User.count(wherestr, function(err, res){
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})
}

//根据ID查询
function getById(id){
User.findById(id, function(err, res){
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})
}
//模糊查询 正则式
function getByRegex(){
var whereStr = {'username':{$regex:/h/}};

User.find(whereStr, function(err, res){
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})
}

//分页查询
function getByPage(){

var pageSize = 1; //一页多少条
var currentPage = 1; //当前第几页
var sort = {'logindate':-1}; //排序(按登录时间倒序)
var condition = {}; //条件
var skipnum = (currentPage - 1) * pageSize; //跳过数

User.find(condition).skip(skipnum).limit(pageSize).sort(sort).exec(function (err, res) {
if (err) {
console.log("Error:" + err);
}
else {
console.log("Res:" + res);
}
})
}
//getCountByConditions();
//update('hu','1111111111111');
//findByIdAndUpdate('5d41745fe9d1bd24eccd53b3','ds');
// getByConditions('hu');
//getCountUsers();
//getById('5d41717ad922db2880efbe4e');
//getByRegex();
//getByPage();


//其它常用方法
Model.distinct(field, [conditions], [callback])//去重
Model.findOne(conditions, [fields], [options], [callback])//查找一条记录
Model.findOneAndRemove(conditions, [options], [callback])//查找一条记录并删除
Model.findOneAndUpdate([conditions], [update], [options], [callback])//查找一条记录并更新