mongoose连接mongodb进行数据库操作详细步骤

1.安装mongoose

npm i mongoose -S||npm install mongoose --save

2.导入mongoose

const mongoose=require('mongoose')

3.连接数据库

//mongoose.connect('mongodb://主机名:端口/数据库名称')
举例:mongoose.connect('mongodb://127.0.0.1:27017/1901')

进一步做连接处理

mongoose.connect('mongodb://127.0.0.1:27017/1901',(err)=>{
     
   if(!err){
     //连接成功了
      console.log('database connect success');
   }else{
     
      throw err;
   }
})

4.存储数据步骤:定义Schema (骨架) > 创建model(模型)> Entity实例化方法。

定义Schema(骨架):

//定义schema
// const teacherSchema = new Schema(options)
/* 
  options
  {
    key:key的数据类型
  }
*/
举例:
const Schema = mongoose.Schema;
const studentsSchema = new Schema({
     
   name: String,
   age: Number,
   sex: String
});

创建model(模型):

//创建模型
// const teacherModel = mongoose.model(集合名称,teacherSchema)
举例:
const studentsModel = mongoose.model('students', studentsSchema);

创建实例:

const studentsInstance = new studentsModel();

5.数据的增删改查:

增加数据:

//数据的存储
studentsInstance.name = 'ksjjsj';
studentsInstance.age = 50;
studentsInstance.sex = 'man';
studentsInstance.save((err) => {
     
    if (!err) {
      //存储成功
        console.log('data save success')
    } else {
     
        throw err
    }
});

删除数据:

//删除数据
studentsModel.find({
      age: 50 }, (err, result) => {
     
    if (!err) {
      //查找成功
        const id = result[0]._id;
        studentsModel.findById(id, (err, docs) => {
     
            if (!err) {
      //删除成功
                docs.remove(() => {
     
                    console.log('data delete success');
                })
            }
        })
    } else {
     
        throw err;
    }
});

修改数据:

//修改数据
studentsModel.find({
      name: 'lcj' }, (err, res) => {
     
    if (!err) {
      //查找成功
        const id = res[0]._id;
        studentsModel.findById(id, (err, docs) => {
     
            docs.age = 18,
                docs.save((err) => {
     
                    if (!err) {
     
                        console.log('data update success')
                    } else {
     
                        throw err
                    }
                })
        })
    } else {
     
        throw err;
    }
});

查找数据:

//查找数据
studentsModel.find({
      age: 50 }, (err, result) => {
     
    if (!err) {
      //查找成功
        console.log('data find success');
        console.log(result);
    } else {
     
        throw err;
    }
});

你可能感兴趣的:(mongodb,数据库,javascript)