连接数据库
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/db530")
.then(()=>{console.log("connect success")})
.catch(err=>console.log(err,"connect fail"));
创建规则
const courseSchema = new mongoose.Schema({
name:String,
id:Number
})
使用规则创建集合
const Course = mongoose.model('Course',courseSchema);
使用集合创建文档
const course = new Course({
name:"Asia",
id:13
})
保存文档
course.save();
create方法创建并添加文档
Course.create({
name:"BBB",
id:12
}).then(result=>{
console.log(result);
}).catch(err=>{
console.log(err);
})
查询
find()无参数默认查询所有,返回文档的集合
Course.find()
.then(result=>{
console.log(result);
})
按属性查询
Course.find({id:12})
.then(data=>console.log(data));
findOne()只返回一条数据,即为find方法返回数组的第一条
Course.findOne({id:12})
.then(data=>console.log(data));
find()范围查询
Course.find({id:{$gt:10,$lt:20}})
.then(data=>{console.log(data)})
find()查询指定字段
Course.find()
.select('name id')
.then(data=>{console.log(data)});
find().sort()按照指定字段排序查询结果,升序排列
Course.find()
.sort("id")
.then(data=>console.log(data));
降序排列
Course.find()
.sort("-id")
.then(data=>console.log(data));
find().skip(2)跳过两条数据
find().limit(3)只查询3条
删除文档
删除单个
findOneAndDelete({id:1})
删除多个
deleteMany({})//删除所有
更新文档
updateOne({查询条件},{要修改的值})
updateMany({查询条件},{要修改的值})