1,启动数据库服务:net start mongodb
2,终止数据库服务:net stop mongodb
3,先再当前文件夹下下载插件: npm install mongoose
3,再js文件中导入模块:const mongoose=require('mongoose');
4,创建数据库连接
mongoose.connect('mongodb://localhost/dejin',{useNewUrlParser:true })
.then(()=>console.log('数据库连接成功'))
.catch(err=>console.log('数据库连接失败',err));
插入数据
1,需要先创建一个集合规则
const courseSchema=new mongooes.Schema({
name:string,
name2:string
})//创建一个集合规则,里面传一个对象,这个对象就是你以后常见数据的格式
2,使用集合规则创建模板
const Course=mongooes.model('Course',courseSchema);
//将架构生成一个模板,后面使用这个模板就可以生成数据;参数:模板名称,模板规则
3,创建数据
- 使用构造函数的方式创建
const course=new Course({
name:'node.js',
author: '得劲',
isPublished: true
});
course.save(); //注意:使用这种方式需要手动调用这个方法将数据插入到数据库中
- 使用create方法创建
Course.create({name:'node.js', author: '得劲', isPublished: true},(err,doc)=>{
console.log(err); //如果插入失败,会打印一个对象,成功打印一个null
console.log(doc);//插入成功打印你插入的数据,失败为null
})
//使用这种方式可以有一个回调函数,所以是一个异步函数,所以能使用Promise的方法,
//