mongose怎么结合node使用和操作数据库

238 阅读1分钟
  1. 安装mongodb
  2. 安装mongose
  3. 开启数据库
            mongod  //注意不是mongodb  
            //默认使用/下的data/db作为数据存储目录 
  1. 关闭数据库 ctrl+c 或关闭命令窗口
  2. 连接数据库
            mongo  //默认连接本机的数据库 但是要先开启数据库
            exit   //在连接之后使用exit退出,不是关闭数据库。
  1. 基本命令
            show dbs //查看所有的数据库
             db //查看所连接的数据库
            use 数据库名称 // 使用数据库,如果没有会新建
            例:use itcarst  表示新建一个数据库 只不过里面没有内容,需要插入一条数据才能通过show dbs 查出来,
            也能通过db来查看当前连接的数据库是itcarst 
            插入数据:db.students.insertOne({name:'sigh',age:22}) 表示你要插入一条students 的数据集合
            注意:是db.xxx  不是itcarst.xxx
            show collections //显示当前db的所有集合
            db.students.find() //查询students里所有的数据
                const mongoose = require('mongoose');
                //连接数据库  默认连接本机的test数据库
                mongoose.connect('mongodb://localhost/test');
                const Cat = mongoose.model('Cat', { name: String }); //这是设计的数据结构模型 相当于做了一个规范
                const kitty = new Cat({ name: 'Zildjian' }); //这里才是插入的数据
                // 这两句代码会在test数据库存里面创建一个集合,虽然现在是大写的,但是最终会转为小写的复数
                // 形式: cats
                //最终得到这种效果
                //use test  db.cats.insertOne({name:'Zildjian'})
                //实例化一个cat
                kitty.save().then(() => console.log('meow'));
                //持久化保存数据