nodejs使用mongodb和mongoose

来源:互联网 发布:中级数据库系统工程师 编辑:程序博客网 时间:2024/04/27 05:30

mongoose官网链接

    • mongodb
      • 启动mongodb
    • nodejs mongoose
      • mongoose modlel 定义数据类型
      • mongoose需要注意的点
      • mongoose基本操作
      • mongoose插入操作
      • mongoose更新操作
      • mongoose删除
      • mongoose查找
      • mongoose查询

mongodb

启动mongodb

#以下启动mongodb为在mac系统中,windows系统换为相应的命令即可sudo mongod# 如果没有创建全局路径 PATH,需要进入以下目录cd /usr/local/mongodb/bin#注意上述路径每个人都不同,需要进入自己的mongodb/bin目录下sudo ./mongod
#进入mongo的shell环境下$ cd /usr/local/mongodb/bin $ ./mongoMongoDB shell version v3.4.2connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.2Welcome to the MongoDB shell.……> 1 + 12> > 

建议下载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.connectiondb.on('error',console.error.bind(console,'connection fail'))db.once('open',function(){    //数据库具体操作代码在这里写})

mongoose插入操作

//先定义modelvar 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输出查询数量
原创粉丝点击