mongodb
启动mongodb
#以下启动mongodb为在mac系统中,windows系统换为相应的命令即可
sudo mongod
# 如果没有创建全局路径 PATH,需要进入以下目录
cd /usr/local/mongodb/bin
#注意上述路径每个人都不同,需要进入自己的mongodb/bin目录下
sudo ./mongod
#进入mongo的shell环境下
$ cd /usr/local/mongodb/bin
$ ./mongo
MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2
Welcome to the MongoDB shell.
……
> 1 + 1
2
>
>
建议下载Robo 3T,mongodb的图形化管理界面,能够更方便的管理操作数据库
nodejs mongoose
mongoose modlel 定义数据类型
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
mongoose需要注意的点
- mongodb只会插入modelSchema定义的点,如果创建对象其他的值是不会放入数据库的
mongoose基本操作
var mongoose=require('mongoose')
mongoose.connect('mongodb://localhost/test')
var db=mongoose.connection
db.on('error',console.error.bind(console,'connection fail'))
db.once('open',function(){
//数据库具体操作代码在这里写
})
mongoose插入操作
//先定义model
var Cat=mongoose.model('Cat',{
name:String,
age:Number,
'hair color':String
})
var kitty=new Cat({
name:'Kitty',
age:3,
'hair color':'white'
})
//对象的操作
kitty.save(function(err,res){
if(err) console.error(err)
else console.log(res)
})
mongoose更新操作
//模型的操作(已定义完模型)
var where={
variety:'Scottish Fold'
}
var update={
'hair color':'black'
}
Cat.update(where,update,function(err,res){
if(err) console.error(err)
else console.log(res)
})
还有专门通过ID查找并更新的方法
var whereById=''
Cat.findByIdAndUpdate(whereById,update,function(err,res)){
if(err) console.error(err)
else console.log(res)
})
mongoose删除
Cat.remove(where,function(err,res))
Cat.findByIdAndRomove(where,function(err,res))
mongoose查找
Cat.find(where,function(err,res))
//res 返回查找到的对象数组
//可以限定输出的内容
var opt={
variety:1
//选择输出的值为1,不输出的值为0(其他不指定默认为0)
}
Cat.find(where,opt,function(err,res))
//var where=_id
Cat.findById(where,function(err,res))
//res 输出查询到的对象
mongoose查询
Cat.count(where,function(err,res))
//res输出查询数量