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 Course.find().then(result=>{console.log(result)}) 16 //根据ID值查找数据,查询结果为数组
17 Course.find({_id:'603c615cf267dd1044ba75b6'}).then(result=>{console.log(result)})
findOne方法,是查询一条数据,默认第一条,可以设置查询条件,但只能查询一条数据,查询结果为对象