mongoose 入门以及 mongoose 实现数据 的增、删、改、查
- mongoose 介绍
Mongoose 是在 node.js 异步环境下对 mongodb 进行便捷操作的对象模型工具。Mongoose 是 NodeJS 的驱动,不能作为其他语言的驱动。
使用顺序
- 安装
npm i mongoose --save
2、引入 mongoose 并连接数据库
const mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/test’); 如果有账户密码需要采用下面的连接方式: mongoose.connect(‘mongodb://eggadmin:123456@localhost:27017/eggcms’);
3、定义 Schema
数据库中的 Schema,为数据库对象的集合。schema 是 mongoose 里会用到的一种数据模式, 可以理解为表结构的定义;每个 schema 会映射到 mongodb 中的一个 collection,它不具备 操作数据库的能力
var UserSchema=mongoose.Schema({
name: String,
age:Number,
status:‘number’
})
4、创建数据模型
mongoose.model(参数 1:模型名称(首字母大写),参数 2:Schema,参数 3:数据库集合名 称)
var User=mongoose.model(‘User’, UserSchema);
实例,对数据库test中的users表进行增删改查
//1.引入mongoose
const mongoose = require('mongoose');
//2.建立连接
mongoose.connect('mongodb://localhost/test', {
useNewUrlParser: true, // 新版本对连接字符串的解析有更好的支持,无此代码会有警告
useUnifiedTopology: true, // 新版本对数据库的监事引擎有更好的支持,无此代码会有警告
});
mongoose.connection.on("open", function() {
console.log("连接已打开");
});
//3.操作users表(集合) 定义一个Schema
var UserSchema = mongoose.Schema({
user: String,
password: String
})
//4.定义数据库模型 操作数据库
//model里面的第一个参数 要注意:1.首字母大写 2.要和数据库表(集合名称对对应)
//这个模型会和模型名称相同的复数的数据库表建立连接:如通过下面 方法创建模型,那么这个模型将会操作 users 这个集合。
var User = mongoose.model('user', UserSchema) //默认会操作users表(集合)
//var User = mongoose.model('User', UserSchema,"user"); // 默认会操作第三个参数配置的表 user表(集合)
//5.查询user表的数据
User.find({}, function(err, doc) {
if (err) {
console.log(err);
return;
}
console.log(doc)
})
//6.增加数据
User.create({
user: "ooo",
password: "ooo"
}, (err, doc) => {
if (err) {
console.log(err);
}
console.log(doc);
})
//7.修改数据
User.updateOne({ "_id": '5f2cb0fb3cd8705330f4a8c8' }, { "user": '哈哈哈' }, function(err, res) {
if (err) {
console.log(err);
return;
}
console.log('成功')
});
//8.删除数据
User.deleteOne({ _id: '5f2cb0fb3cd8705330f4a8c8' }, function(err) {
if (err) {
console.log(err);
return;
}
console.log('成功');
});
mongoose 预定义模式修饰符(数据校验)
主要有lowercase、uppercase 、trim
mongoose 提供的预定义模式修饰符,可以对我们增加的数据进行一些格式化。
required : 表示这个数据必须传入
max: 用于 Number 类型数据,最大值
min: 用于 Number 类型数据,最小值
enum:枚举类型,要求数据必须满足枚举值 enum: [‘0’, ‘1’, ‘2’] 用在String类型上
match:增加的数据必须符合
match(正则)的规则
maxlength:最大值
minlength:最小值
var UserSchema = mongoose.Schema({
user: {
type: String,
required: true, //必填
unique: true, //属性值唯一
trim: true, //写入数据时,会自动的去掉首尾空格
minlength: 3, //约束,字符串的最小长度为3
maxlength: 18, //约束,字符串的最大长度为18
enum: ['0', '1', '2'],// 设置字符串的可选值
match: /^\d{11}$/,
// 自定义的验证器,如果通过验证返回 true,没有通过则返回 false
validate: function(desc) {
return desc.length >= 10;
}
},
password: String
})
Mongoose Getters 与 Setters 自定义修饰符
除了 mongoose 内置的修饰符以外,我们还可以通过 set(建议使用) 修饰符在增加数据的 时候对数据进行格式化。也可以通过 get(不建议使用)在实例获取数据的时候对数据进行格式化。
- 例子:
当用户输入一个地址时,假如输入http://www.baidu.com时,数据库存储http://www.baidu.com。
当用户输入一个地址时,假如输入www.baidu.com时,数据库也存储http://www.baidu.com。
var NewsSchema = mongoose.Schema({
title: "string",
author: String,
pic: String,
redirect: {
type: String,
set(url) { //增加数据的时候对redirect字段进行处理
//url可以获取redirect的值,返回的数据就是redirect在数据库实际保存的值
if (!url) return url;
if (url.indexOf('http://') != 0 && url.indexOf('https://') != 0) {
url = 'http://' + url;
}
return url;
}
},
content: String,
status: {
type: Number,
default: 1
}
})
- Mongoose 索引
索引是对数据库表中一列或多列的值进行排序的一种结构,可以让我们查询数据库变得更 快。MongoDB 的索引几乎与传统的关系型数据库一模一样,这其中也包括一些基本的查询 优化技巧。
var DeviceSchema = new mongoose.Schema({
sn: {
type: Number, // 唯一索引
unique: true
},
name: {
type: String, // 普通索引
index: true
}
});
- 扩展 Mongoose CURD 方法
var mongoose = require('./db.js');
var UserSchema = mongoose.Schema({
name: {
type: String
},
age: Number,
status: {
type: Number,
default: 1
}
})
// 静态方法
//根据数据库中的uid值查找相关的数据
UserSchema.statics.findByUid = function(uid, cb) {
//通过find方法获取uid的数据 this关键字获取当前的model
this.find({ "uid": uid }, function(err, docs) {
cb(err, docs)
})
}
// 实例方法 (用的少,基本不用)
UserSchema.methods.print = function() {
console.log('这是一个实例方法');
console.log(this);
};
module.exports = mongoose.model('User', UserSchema, 'user');
// 调用
UserSchema.findByUid("124213", (err, doc) => {
if (err) {
console.log(err);
}
console.log(doc);
})