为什么要用mongoose?
mongodb数据格式过于灵活,实际项目开发时,要有数据格式规范;mongoose可提供规范(schema定义数据格式的规范;以Model规范Collection,规范数据操作的API)
-
安装mongoose插件:
a. 到 npm官网 搜mongoose
b. 控制台中执行npm i mongoose --save
-
使用mongoose:
a. 新建一个文件夹db并新建一个文件db.js: 用来连接数据库
b. 建立数据连接:db.js中
// 连接数据库(mongodb的服务端)
// 获取mongoose插件
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017';
const dbName = 'comment2'
// 连接数据库
mongoose.connect(`${url}/${dbName}`, {
useNewUrlParser: true,
useUnifiedTopology: true
});
// 获取当前的连接对象
const conn = mongoose.connection;
// 监听错误
conn.on('error', err => {
console.error('mongoose连接出错', err)
})
module.exports = mongoose;
c. 新建一个文件作为数据模型:model.js,在其中定义数据模型
// 数据模型(规范数据格式)
const mongoose = require('./db')
// 定义schema(数据规范)
const UserSchema = mongoose.Schema({
username: {
type: String,
required: true, // 必填
unique: true // 唯一,不重复
},
password: String,
age: Number,
city: String,
gender: {
type: Number,
default: 0 // 设置默认值,0-保密,1-男,2-女
}
}, {
timestamps: true // 时间戳,自动添加文档的创建时间
})
// 定义Model
const User = mongoose.model('user', UserSchema)
module.exports = {
User
}
c. 使用schema model操作数据(新建一条数据):新建一个test1.js文件
// 使用model操作数据
const {User} = require('./model')
// 定义一个async的匿名函数,并执行。为了里面能用await
!(async() => {
// 新增数据
const zhangsan = new User({
username: 'zhangsan',
password: 'abc',
age: 20,
city: 'beijing',
gender: 1
})
// 保存下来
zhangsan.save()
})()
在控制台中输入node db/test1/js
,执行新增数据,之后到compass中查看是否新增成功
如上新增一条zhangsan数据
d. 新建数据方法二:
!(async() => {
// 新增数据
// const zhangsan = new User({
// username: 'zhangsan',
// password: 'abc',
// age: 20,
// city: 'beijing',
// gender: 1
// })
// // 保存下来
// zhangsan.save()
// 另一种新增数据的方法
const lisi = await User.create({
username: 'lisi',
password: 'abc',
age: 20,
city: 'beijing',
})
console.log('lisi创建完成', lisi)
})()
e. 查询列表数据,返回的是数组
!(async() => {
// 新增数据-1
// const zhangsan = new User({
// username: 'zhangsan',
// password: 'abc',
// age: 20,
// city: 'beijing',
// gender: 1
// })
// // 保存下来
// zhangsan.save()
// 另一种新增数据的方法-2
// const lisi = await User.create({
// username: 'lisi',
// password: 'abc',
// age: 20,
// city: 'beijing',
// })
// console.log('lisi创建完成', lisi)
// 查询数据
const userList = await User.find()
console.log('user list查询结果', userList)
})()
f. 带条件的查询:
const userList = await User.find({username: 'zhangsan'})
console.log('user list查询结果', userList)
g. 排序:
// 排序
const userList = await User.find().sort({age: -1})
console.log('user list查询结果', userList)
h. 查询单条数据,返回的对象:
// 查询单条数据
const user = await User.findOne({username: 'zhangsan'})
console.log('user查询结果', user)