ちょうきょう666

导航

1、连接数据库,插入数据

 1 const mongoose=require('mongoose')
 2 //链接数据库,成功运行then里面的代码,错误运行catch里面的代码
 3 mongoose.connect("mongodb://localhost/playground",{ useNewUrlParser: true,useUnifiedTopology: true})
 4 .then(()=>{console.log("数据库连接成功")})
 5 .catch(err=>{console.log(err,'数据库失败')})
 6 //创建集合规则,返回构造函数
 7 const courseSchema= new mongoose.Schema({
 8     name:String,
 9     author:String,
10     isPublished:Boolean
11 });
12 //使用规则创建集合,参数1是集合名,2是规则
13 const Course= mongoose.model("Course",courseSchema)
14 //实例化集合,创建文档
15 const course= new Course({
16     name:"node.js",
17     author:"ZG",
18     isPublished:true
19 
20 });
21 //将文档插入到数据库里
22 course.save();

 

posted on 2021-03-01 12:55  ちょうきょう666  阅读(88)  评论(0编辑  收藏  举报