mongose 教程
1.安装
npm install mongoose --save
2.连接mongodb
const mongoose = require("mongoose")
mongoose.connect("mongodb://[username]:[password]@[host]:[port]/[dbname]",{
useNewUrlParser: true
})
3.创建模型
const mongoose = require("mongoose")//这里所引用的mongose是上面连接创建出来的mongose常量
const schema = new mongoose.Schema({
type:{type:String},
name:{type:String},
})
module.exports = mongoose.model("BillSet",schema)
设置字段不查询,并且写入转换
const mongoose = require("mongoose")
const schema = new mongoose.Schema({
username:{type:String},
password:{type: String,select:false,set(val){
return require('bcrypt').hashSync(val,10)
}}
})
module.exports = mongoose.model("AdminUser",schema)
4.数据操作
下面是先获取定义的mongo模型
const modelName = require("inflection").classify(req.params.resource)
req.model = require(`../models/${modelName}`)
4.1 查询
$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个元素
4.1.1 find()
# conditions 查询条件、fields 想要查询的字段、options 、callback 回调函数
Model.find(conditions, [fields], [options], [callback])
#demo
userModel.find({'name':'张三'},{'name':1,'sex':1,'region':1,'createBy':1,'_id':0})
.skip(1).limit(2).sort({'createBy.createTime' : -1})
# 查询条件:{'name':'张三'}
# 显示的字段:{'name':1,'sex':1,'region':1,'createBy':1,'_id':0}
# 从第二条数据开始: .skip(1)
# 取两条数据: .limit(2)
# 排序方式: .sort({'createBy.createTime' : -1})
# 还有另一种方式
userModel.find({'name':'张三'},
{'name':1,'sex':1,'region':1,'createBy':1,'_id':0},
{ limit:2, skip:1, sort:'-createBy.createTime'})
# 查询非空字段
Model.find(conditions:{$exists:true})
Model.find(conditions:{$ne:null})
# 分页查询
Model.find(conditions).skip(pageTotal * pageNum).limit(pageTotal).sort({'_id':-1}).exec(cb);
# 模糊查询
userModel.find({"name" : {$regex:'大虾'}})
userModel.find({"name" : /大虾/ }})
4.1.2 where
find({$where : "this.name == 'a'"})
Model.$where('this.firstname === this.lastname').exec(callback)
Model
.where('age').gte(25)
.where('tags').in(['movie', 'music', 'art'])
.select('name', 'age', 'tags')
.skip(20)
.limit(10)
.asc('age')//排序
.slaveOk()//允许此连接从副本对的非主membr读取
.hint({ age: 1, name: 1 }) //强制使用索引
.run(callback);
4.1.3 findById()
Model.findById(conditions, [fields], [options], [callback])
# 与 Model.find 相同,但它接收文档的 _id 作为参数,返回单个文档。_id 可以是字符串或 ObjectId 对象
4.1.4 findOne()
Model.findOne(conditions, [fields], [options], [callback])
# 与 Model.find 相同,但只返回符合条件的第一个文档
4.2 插入
4.2.1 model.create()
TestModel.create(
{ candy: 'jelly bean' },
{ candy: 'snickers' },
function (err, jellybean, snickers) {
});
4.2.2 Model.collection.insert( )
insert( ) 在新版本已经被替换了,替换成insertOne()和insertMany()
Model.collection.insert(docs, options, callback)
# docs - 要插入的文档是数组
# options - 可选的配置对象- 请参见 docs
# callback(err, docs) - 保存完所有文档或出现错误后调用,获取之后, 将调用否则出错。 如果成功, docs 是文档的保存的数组
4.3 删除
4.3.1 删除查询到的第一个文档
Model.remove(conditions,callback);
Model.deleteOne(conditions,callback);
4.3.2 删除符合条件的所有文档
Model.deleteMany(conditions,callback);
4.4 汇总
Model.count(conditions,callback);