Mongoose是在node.js环境下对mongodb进行便捷操做的对象模型工具javascript
一开始须要安装node.js环境以及mongodb数据库,而后建立mongdb数据文件夹而且启动mongdb(windows安装启动mongodb)。html
connect 用于链接数据库java
mongoose.connect(uri(s), [options], [callback])
//url(s):数据库地址,能够是多个,以`,`隔开
//options:可选,配置参数
//callback:可选,回调
// 规则
mongoose.connect('mongodb://数据库地址(包括端口号)/数据库名称')
// 链接mongodb示例
mongoose.connect('mongodb://localhost:27017/db'); //链接本地默认27017端口的mongodb
//链接指定用户链接示例
mongoose.connect('mongodb://用户名:密码@127.0.0.1:27017/数据库名称')
//链接多个数据库示例
//若是你的app中要链接多个数据库,只须要设置多个url以,隔开,同时设置mongos为true
mongoose.connect('urlA,urlB,...', {
mongos : true
})
复制代码
schema能够理解为mongoose对表结构的定义(不单单能够定义文档的结构和属性,还能够定义文档的实例方法、静态模型方法、复合索引等),每一个schema会映射到mongodb中的一个collection,schema不具有操做数据库的能力node
const mongoose = require('mongoose');
const {Schema} = mongoose;
// 用户对象模型
const userSchema = new Schema({
name: {
type: String, //类型
default: Date.now // 默认值
},
avatar: {
type: String,
required: true //必须有值
},
user: String,
passworld: String,
hash: String,
score: Number,
learn: Array,
message: Array,
star: Array,
sign: Array,
signdate: String,
isregister: Boolean,
});
复制代码
schema字段类型mongodb
Model是由Schema编译而成的假想(fancy)构造器,具备抽象属性和行为。Model的每个实例(instance)就是一个document。document能够保存到数据库和对数据库进行操做。数据库
//建立并导出model
const db= {
User: mongoose.model('MUser', muserSchema),
};
module.exports = db;
复制代码
如今咱们就完成了mongodb的数据链接,数据对象模型的建立。json
引入以前导出的模型mongodb数据const db = require('../models/db')
windows
find用来查询并输出该条件下的全部文档 db.Userl.find({conditions}, {options}, callback)
conditions Object类型 //查询条件 options Object 类型 //查询配置参数 callback Function //回调数组
// 查询Article模型下全部数据
db.Article.find({}, function(err, docs){
if (err) {
console.log('出错'+ err);
return;
}
res.json(docs); // 以json格式输出
});
// 查询Article模型下state字段为'publish'的内容,而且不输出articleContent和user字段内容。注!(1为只输出该字段,0为不输出该字段)
db.Article.find({state: "publish"}, {articleContent: 0,user: 0}, function(err, docs){
if (err) {
console.log('出错'+ err);
return;
}
res.json(docs);
});
//查询阅读量大于500小于600的文章
db.Article.find(({views: {$gte: 500, $lte: 600}}), function(err, docs){
if (err) {
console.log('出错'+ err);
return;
}
res.json({data:docs});
})
// 复杂条件查询
//$ro 查询该模型下的title字段或者tag字段,$regex 为正则匹配实现模糊查询,$options为不区分大小写
db.Article.find({ $or: [{title: {$regex: searchval, $options:'i'} }, { tag: {$regex: searchval, $options:'i' }}] }}, function(err, docs){
if (err) {
console.log('出错'+ err);
return;
}
res.json({data:docs});
})
复制代码
与find相似,但只返回单个文档app
db.Article.findOne({title: req.body.title}, function(err, docs){
if (err) {
console.log('出错'+ err);
}
res.json(docs);
})
复制代码
与findOne相似,但它接收文档的 _id 做为参数,返回单个文档。_id 能够是字符串或 ObjectId 对象。
db.Article.findOne(id, function(err, docs){
if (err) {
console.log('出错'+ err);
}
res.json(docs);
})
复制代码
返回符合条件的文档数。
db.Article.count(id, function(err, docs){
if (err) {
console.log('出错'+ err);
}
res.json(docs);
})
复制代码
当查询比较复杂时,用 where:
db.Article.where('age').gte(25)
.where('tags').in(['movie', 'music', 'art'])
.select('name', 'age', 'tags')
.skip(20)
.limit(10)
.asc('age')
.slaveOk()
.hint({ age: 1, name: 1 })
.run(function(err, docs){
if (err) {
console.log('出错'+ err);
}
res.json(docs);
}));
复制代码
有时咱们须要在 mongodb 中使用 javascript 表达式进行查询,这时能够用 find({$where : javascript})
方式,$where 是一种快捷方式,并支持链式调用查询。
db.MUser.$where('this.firstname === this.lastname').exec((err, docs) => {
res.json({docs});
});
复制代码
sort为排序方法,为该字段正序或者倒序输出内容(-1为倒序) skip为跳过多少条目 limit 为限制输出多少条
// 实现文章分页,按时间倒序排列输出
db.Article.find({tag:req.params.labe}, function(err, docs){
if (err)return;
res.json(docs)
}).sort({date:-1}).skip(page*pagenum).limit(pagenum)
复制代码
save是一个实例方法,使用时须要先 new Model() 来实例化
//保存一个用户信息,userobj为你建立的文档对象模型里的字段,需正确对应传入
const userobj={
email: query,
passworld: req.body.passworld,
hash: hash,
isregister: false,
score: 5,
sign: [],
signdate: ''
}
new db.MUser(userobj).save(function(error){
if (error) {
res.status(500).send()
return
}
res.json({statu: 200})
})
复制代码
删除数据方法
db.Course.remove({_id: req.body.id}, function(err, docs){
if (err) {
res.status(500).send();
return
}
res.json({statu: 200})
})
复制代码
更新数据方法
// 更新指定email字段数据条目下字段为content的内容,若是不存在就建立该字段
db.Share.update({email: email},{$set:{content: newarr}}, function(err, docs){
if (err) {
res.status(500).send();
return
}
res.json({statu: 200});
})
//$set 指定字段的值,这个字段不存在就建立它。能够是任何MondoDB支持的类型。
Article.update({_id : id}, {$set : {views : 51, title : ‘修改后的标题’ …}})
//$unset 同上取反,删除一个字段
Article.update({views : 50}, {$unset : {views : ‘remove’}})
//执行后: views字段不存在
//$inc 增减修改器,只对数字有效。
Article.update({_id : id}, {$inc : {views : 1}})
//$push 为字段为数组的内容push数据
Article.update({_id : id}, {$push : {message : messageobj}})
//$pop从头部或尾部删除单个元素(1为从后面删除,-1为从前面删除)
db.Article.update(({_id: id), {$pop:{relationships: -1})
//__$pull__删除知足条件的元素,不止删除一个
db.Article.update(({_id: id), {$pull:{“relationships”:{“fname”:”dongren”, ”lname”: ”zeng”}}})
复制代码
$set 指定字段的值,这个字段不存在就建立它。能够是任何MondoDB支持的类型。
Article.update({_id : id}, {$set : {views : 51, title : '修改后的标题' ...}})
$unset 同上取反,删除一个字段
Article.update({views : 50}, {$unset : {views : 'remove'}})
//执行后: views字段不存在
$inc 增减修改器,只对数字有效。
Article.update({_id : id}, {$inc : {views : 1}})
$push 为字段为数组的内容push数据
Article.update({_id : id}, {$push : {message : messageobj}})
$pop 从头部或尾部删除单个元素(1为从后面删除,-1为从前面删除)
db.Article.update(({_id: id), {$pop:{relationships: -1})
$pull 删除知足条件的元素,不止删除一个
db.Article.update(({_id: id), {$pull:{“relationships”:{“fname”:”dongren”, ”lname”: ”zeng”}}})