mongoose 介绍
mongoose 是用来操作 MongoDB 数据库的开源 ORM 框架
快速体验
安装:
npm install mongoose express
连接数据库:
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true,useUnifiedTopology: true});const db = mongoose.connection;db.on('error', console.error.bind(console, '连接失败:'));db.once('open', function() {// we're connected!console.log('连接成功')});
定义 Schema:
const kittySchema = new mongoose.Schema({name: String});
将 Schema 发布为 Model:
const Kitten = mongoose.model('Kitten', kittySchema);
使用 Model 操作数据库:
// 添加const fluffy = new Kitten({ name: 'fluffy' });fluffy.save().then(...)// 查询Kitten.find().then(...)// 更新Kitten.findOneAndUpdate({}, // 查询条件{} // 更新数据).then(...)// 删除Kitten.findOneAndDelete({} // 条件).then(...)
Schemas
参考:https://mongoosejs.com/docs/guide.html。
SchemaTypes
参考:https://mongoosejs.com/docs/schematypes.html。
Connections
参考:https://mongoosejs.com/docs/connections.html。
Models
参考:https://mongoosejs.com/docs/models.html。
Documents
参考:https://mongoosejs.com/docs/documents.html。
Subdocuments
参考:https://mongoosejs.com/docs/subdocs.html。
Queries
参考:https://mongoosejs.com/docs/queries.html。
Validation
参考:https://mongoosejs.com/docs/queries.html。
