一、连接数据库
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/zx', { useNewUrlParser: true })
.then(() => console.log('成功'))
.catch(err => console.log(err, '失败'));
命令行执行,返回成功则成功连接到数据库。
二、创建集合
创建users集合
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String]
});
const users = mongoose.model('users', userSchema);
三、查询文档
1.查询用户集合中的所有文档
users.find().then(result => console.log(result));
2.通过指定的字段查找文档
uesrs.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
3.findOne方法返回一条文档 默认返回当前集合中的第一条文档
users.findOne({ name: '李四' }).then(result => console.log(result))
4、 .find({字段: {$gt: 大于, $lt: 小于}})查询一个区间内的文档
users.find({ age: { $gt: 10, $lt: 30 } }).then(result => console.log(result));
5、 find({字段: {$in: [‘包含的字段’]}})查询包含指定字段的文档
users.find({ hobbies: { $in: ['橄榄球'] } }).then(result => console.log(result))
6、.select(‘字段 -字段’)只查询出制定的字段 加-不查询
users.find().select('age name -_id').then(result => console.log(result))
7、 .sort(‘字段’)按照升序排列文档 所有的文档 不只是查询的文档
users.find().sort('age').then(result => console.log(result))
8、 字段前加-降序排列
users.find().sort('-age').then(result => console.log(result))
9、.skip(n).limit(m) 查询到的文档 跳过前n条显示前m条
users.find().skip(3).limit(3).then(result => console.log(result))