MongoDB数据库导入数据
mongoimport –d 数据库名称 –c 集合名称 –file 要导入的数据文件
找到mongodb数据库的安装目录,将安装目录下的bin目录放置在环境变量中。
例如: mongoimport -d playground -c users --file user.json
查询文档
// 根据条件查找文档(条件为空则查找所有文档)
Course.find().then(result => console.log(result))
// 根据条件查找文档
Course.findOne({name: 'node.js基础'}).then(result => console.log(result))
// 匹配大于 小于
User.find({age: {$gt: 20, $lt: 50}}).then(result => console.log(result))
// 匹配包含
User.find({hobbies: {$in: ['打球']}}).then(result => console.log(result))
// 选择要查询的字段
User.find().select('name email').then(result => console.log(result))
// 将数据按照年龄进行排序
User.find().sort('age').then(result => console.log(result))
// skip 跳过多少条数据 limit 限制查询数量
User.find().skip(2).limit(2).then(result => console.log(result))
删除文档
// 删除单个
Course.findOneAndDelete({}).then(result => console.log(result))
// 删除多个
User.deleteMany({}).then(result => console.log(result))**
更新文档
// 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
// 更新多个
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))
mongoose验证
在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。
required: true 必传字段
minlength:3 字符串最小长度
maxlength: 20 字符串最大长度
min: 2 数值最小为2
max: 100 数值最大为100
enum: ['html', 'css', 'javascript', 'node.js']
trim: true 去除字符串两边的空格
validate: 自定义验证器
default: 默认值