MongoDB快速上手指南: Nodejs 中使用 MongoDB – mongoose

2022-08-0222:22:32编程语言入门到精通Comments985 views字数 2386阅读模式

mongoose 是一个对象文档模型(ODM)库文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

mongoosejs.com/文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

  • 可以为文档创建一个模式结构(Schema)
  • 可以对模型中的对象/文档进行验证
  • 数据可以通过类型转换转换为对象模型
  • 可以使用中间件应用业务逻辑

6.1 mongoose 提供的新对象类型

  • Schema
    • 定义约束了数据库中的文档结构
    • 个人感觉类似于 SQL 中建表时事先规定表结构
  • Model
    • 集合中的所有文档的表示, 相当于 MongoDB 数据库中的 collection
  • Document
    • 表示集合中的具体文档, 相当于集合中的一个具体的文档

6.2 简单使用 Mongoose

mongoosejs.com/docs/guide.…文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

使用 mongoose 返回的是一个 mogoose Query object, mongoose 执行 query 语句后的结果会被传进 callback 函数 callback(error, result)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

A mongoose query can be executed in one of two ways. First, if you pass in a callback function, Mongoose will execute the query asynchronously and pass the results to the callback.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

A query also has a .then() function, and thus can be used as a promise.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

const q = MyModel.updateMany({}, { isDeleted: true }, function() {
  console.log("Update 1");
}));

q.then(() => console.log("Update 2"));
q.then(() => console.log("Update 3"));
复制代码

上面这一段代码会执行三次 updateMany() 操作, 第一次是因为 callback, 之后的两次是因为 .then() (因为 .then() 也会调用 updatemany())文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

连接数据库并且创建 Model 类文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

const mongoose = require('mongoose');
// test is the name of database, will be created automatically
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});

const Cat = mongoose.model('Cat', { name: String });

const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));
复制代码

监听 MongoDB 数据库的连接状态文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

在 mongoose 对象中, 有一个属性叫做 connection, 该对象就表示数据库连接.通过监视该对象的状态, 可以来监听数据库的连接和端口文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

mongoose.connection.once("open", function() {
  console.log("connection opened.")
});

mongoose.connection.once("close", function() {
  console.log("connection closed.")
});
复制代码

6.3 Mongoose 的 CRUD

首先定义一个 Schema文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const blogSchema = new Schema({
    title:  String, // String is shorthand for {type: String}
    author: String,
    body:   String,
    comments: [{ body: String, date: Date }],
    date: { type: Date, default: Date.now },
    hidden: Boolean,
    meta: {
        votes: Number,
        favs:  Number
    }
});
复制代码

然后在 blogSchema 基础上创建 Model文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

const Blog = mongoose.model('Blog', blogSchema);
// ready to go!

module.exports = Blog;
复制代码

当调用上面这一行代码时, MongoDB 会做如下操作文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

  1. 是否存在一个数据库叫做 Blog 啊? 没的话那就创建一个
  2. 每次用到 Blog 库的时候都要注意内部数据要按照 blogSchema 来规定

向数据库中插入文档数据文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

Blog.create({
  title: "title"
  ...
}, function (err){
  if (!err) {
    console.log("successful")
  }
});
复制代码

简单的查询一下下文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

// named john and at least 18 yo
MyModel.find({ name: 'john', age: { $gte: 18 }});
复制代码

mongoose 支持的用法有:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

作者:是小梁同学呀
来源:稀土掘金文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26461.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/26461.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定