mongose 简单使用

1.安装 2.连接mongodb 3.创建模型 设置字段不查询,并且写入转换 4.数据操作 下面是先获取定义的…

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 查询

𝑜𝑟或关系ornor 或关系取反
𝑔𝑡大于gtgte 大于等于
𝑙𝑡小于ltlte 小于等于
𝑛𝑒不等于nein 在多个值范围内
𝑛𝑖𝑛不在多个值范围内ninall 匹配数组中多个值
𝑟𝑒𝑔𝑒𝑥正则,用于模糊查询regexsize 匹配数组大小
𝑚𝑎𝑥𝐷𝑖𝑠𝑡𝑎𝑛𝑐𝑒范围查询,距离(基于𝐿𝐵𝑆)maxDistanceLBSmod     取模运算
𝑛𝑒𝑎𝑟邻域查询,查询附近的位置(基于𝐿𝐵𝑆)nearLBSexists 字段是否存在
𝑒𝑙𝑒𝑚𝑀𝑎𝑡𝑐ℎ匹配内数组内的元素elemMatchwithin 范围查询(基于LBS)
𝑏𝑜𝑥范围查询,矩形范围(基于𝐿𝐵𝑆)boxLBScenter 范围醒询,圆形范围(基于LBS)
𝑐𝑒𝑛𝑡𝑒𝑟𝑆𝑝ℎ𝑒𝑟𝑒范围查询,球形范围(基于𝐿𝐵𝑆)centerSphereLBSslice 查询字段集合 中的元素(比如从第几个之后,第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" : /大虾/ }})
AI写代码js12345678910111213141516171819202122232425
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);

Previous Post

Next Post

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

About the Author

每个人都有自己得时区,在自己得时区里,一切都是准时的。

BlockSpare — News, Magazine and Blog Addons for (Gutenberg) Block Editor