宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

一、安装和配置

Mongoose是一个强大的Node.js库,它提供了对MongoDB数据库的操作。要使用Mongoose,首先需要安装和配置。

1.安装Mongoose


npm install mongoose

使用npm安装mongoose库。

2.连接到MongoDB数据库


const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/my_database', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('MongoDB connected!');
});

使用Mongoose连接到MongoDB数据库,可以使用以上代码。

二、定义模式(Schema)

在Mongoose中,Schema是以数据架构的方式定义的。

1.定义Schema


const mongoose = require('mongoose');

const movieSchema = new mongoose.Schema({
  title: String,
  director: String,
  year: Number
});

const Movie = mongoose.model('Movie', movieSchema);

使用above code for defining a Schema。

2.使用Schema中的类型

在Schema中可以使用多种不同类型的属性。


const schema = new mongoose.Schema({
  name: String,
  age: Number,
  bio: {
    type: String,
    validate: function(text) {
      return text.length <= 50;
    }
  },
  dateOfBirth: Date,
  friends: [String],
  education: [{
    degree: String,
    school: String,
    year: Number
  }],
  address: {
    street: String,
    city: String,
    state: String,
    country: String
  }
});

以上代码示例展示了使用Mongoose Schema中的不同类型和验证属性。

三、模型(Model)

在Mongoose中,Model定义了Schema的实例,用于对数据库进行操作。

1.定义Model


const mongoose = require('mongoose');

const movieSchema = new mongoose.Schema({
  title: String,
  director: String,
  year: Number
});

const Movie = mongoose.model('Movie', movieSchema);

使用上述代码定义一个Movie模型。

2.定义Model实例


const movie1 = new Movie({ title: 'Alien', director: 'Ridley Scott', year: 1979 });
const movie2 = new Movie({ title: 'Blade Runner', director: 'Ridley Scott', year: 1982 });

使用以上代码定义两个Movie实例。

四、CRUD 操作

Mongoose库提供了ORM方式对MongoDB的CRUD(增删改查)操作。

1.创建(Create)


const movie = new Movie({ title: 'E.T.', director: 'Steven Spielberg', year: 1982 });

movie.save(function (err, movie) {
  if (err) return console.error(err);
  console.log('成功添加电影到数据库!');
});

使用以上代码向MongoDB中添加一部电影。

2.读取(Read)


Movie.find({}, function (err, movies) {
  if (err) return console.error(err);
  console.log(movies);
});

使用以上代码读取MongoDB数据库中的所有电影。

3.更新(Update)


Movie.updateOne({ title: 'E.T.' }, { director: 'John Doe' }, function (err, result) {
  if (err) return console.error(err);
  console.log(result.nModified + ' 条文档被更新。');
});

使用以上代码将一条电影文档的导演修改为”John Doe”。

4.删除(Delete)


Movie.deleteOne({ title: 'E.T.' }, function (err) {
  if (err) return console.error(err);
  console.log('电影文档被删除。');
});

使用以上代码从MongoDB中删除电影文档。

五、插件

Mongoose库允许开发者编写自己的插件,以增强Mongoose的功能。

1.编写插件


const mongoose = require('mongoose');
const beautifyUnique = require('mongoose-beautiful-unique-validation');

mongoose.plugin(beautifyUnique);

const movieSchema = new mongoose.Schema({
  title: {
    type: String,
    unique: true
  },
  director: String,
  year: Number
});

const Movie = mongoose.model('Movie', movieSchema);

使用以上代码编写一个插件,美化独特性验证错误消息(beautifyUnique)。

2.使用插件


const movie = new Movie({ title: 'E.T.', director: 'Steven Spielberg', year: 1982 });
movie.save(function (err) {
  console.log(err.message); // 'E.T.已经被使用。'
});

使用以上代码验证插件是否生效。

总结

本文全面解读了Mongoose中文文档的特性,从如何安装和配置开始,逐步介绍了Schema,Model,CRUD操作以及插件等。无论是新手还是有经验的开发人员都可以通过本文深入了解Mongoose库。