mongoose 介绍

mongoose 是用来操作 MongoDB 数据库的开源 ORM 框架

快速体验

安装:

  1. npm install mongoose express

连接数据库:

  1. const mongoose = require('mongoose');
  2. mongoose.connect('mongodb://localhost/test', {
  3. useNewUrlParser: true,
  4. useUnifiedTopology: true
  5. });
  6. const db = mongoose.connection;
  7. db.on('error', console.error.bind(console, '连接失败:'));
  8. db.once('open', function() {
  9. // we're connected!
  10. console.log('连接成功')
  11. });

定义 Schema:

  1. const kittySchema = new mongoose.Schema({
  2. name: String
  3. });

将 Schema 发布为 Model:

  1. const Kitten = mongoose.model('Kitten', kittySchema);

使用 Model 操作数据库:

  1. // 添加
  2. const fluffy = new Kitten({ name: 'fluffy' });
  3. fluffy.save().then(...)
  4. // 查询
  5. Kitten.find().then(...)
  6. // 更新
  7. Kitten.findOneAndUpdate(
  8. {}, // 查询条件
  9. {} // 更新数据
  10. ).then(...)
  11. // 删除
  12. Kitten.findOneAndDelete(
  13. {} // 条件
  14. ).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

Populate

参考:https://mongoosejs.com/docs/populate.html