// 首先设置环境变量path 以便向执行数据库命令 向数据库中导入数据 // mongoimport -d 数据库名 —c 集合名 --file 文件名 // 查询数据库中的文档 // 数据库实例对象.find()查询数据库 const mongoose = require('mongoose') //引入mongoose模块 // 因为mongose链接返回的是promise对象 mongoose.connect('mongodb://localhost/wrj', { useNewUrlParser: true //选项 新的解析器 可选 }) .then(() => { console.log('数据库连接成功'); }) .catch(err => console.log('数据库连接失败')) // mongoose.Schema构造函数实例创建集合 插入的文档必定属于某个集合 // 一.插入文档之第一种方法 //设定集合规则 const courseSchema = new mongoose.Schema({ name: String, age: Number, email: String, password: String, hobbies: [String] }); const couse = mongoose.model('wrjs', courseSchema); //返回的是一个数组 可以包含多条数据 couse.find().then(result => console.log(result)); // 还可以定义条件查询文档 比如id couse.find({_id:'5c09f267aeb04b22f8460968'}).then(result =>console.log(result) ) //返回的是一个对象 只能包含一条数据 默认返回第条文档 couse.findOne().then(reslut => console.log(result)) // 这种方法也可以自定义条件查询 couse.findOne({_id:'5c09f267aeb04b22f8460968'}).then(result =>console.log(result)
//根据年龄条件来查询 大于20 小于40
coures.find({age:{$gt:20,$lt:40}}).then(result => console.log(result))
//根据包含情况来查询
coures.find({hobbies:{$in :['足球']}}).then(result => console.log(result))
// 根据字段来查询 字段前有_的 默认会自动查询 比如id
coures.find().select('查询字段名 比如name age').then(result => console.log(result))
//若不想查询某个字段 在其前面加-
coures.find().select('-_id').then(result => console.log(result))
//根据某个字段排序查询 升序 比如年龄
coures.find().sort('age').then(result => console.log(result))
// 降序排序 在查询字段前加上-
coures.find().sort('-age').then(result => console.log(result))
//skip跳过前几个文档 limit限制查询数量 比如跳过前两个文档 只查询当前文档的3条数据
coures.find().skip(2).limit(3).then(result => console.log(result))
删除数据库
course.findByIdAndDelete({ _id: '5c09f267aeb04b22f8460968' }).then(() => console.log('删除数据成功')) //删除多条文档 大中括号里没有参数时 默认删除数据库中所有文档 返回一个对象 n 删除文档属 ok =1 表示删除文档成功 course.deleteMany({}).then(result => console.log(result))