Mongoose介绍

官网

Mongoose.js中文网 (mongoosejs.net)

基本使用

安装

最新的是mongoose8.0.0版本,基于Promise,以前的版本是基于回调函数。

  • npm
npm i mongoose
  • yarn
yarn add mongoose

使用

以mongoose8.0.0举例:

// 1-引入mongoose
const mongoose = require("mongoose");

// 2-连接数据库
mongoose
    .connect("mongodb://127.0.0.1:27017/test")
    .then(() => {
        console.log("数据库连接成功!");

        // 3-创建结构
        const userSchema = new mongoose.Schema({
            id: {
                type: Number,
                index: true,
                unique: true,
            },
            name: String,
        });

        // 4-创建模型
        const userModel = mongoose.model("user", userSchema);

        // 5-对数据库进行操作
        // 增
        const user = new userModel({
            id: 1,
            name: "kaka",
        });
        userModel.create(user);
    })
    .catch(() => {
        console.log("数据库连接失败!");
    });

字段

字段类型

文档结构可选的常用字段类型列表

类型 描述
String 字符串
Number 数字
Boolean 布尔值
Array 数组,也可以使用[]来标识
Date 日期
Buffer Buffer对象
Mixed 任意类型,需要使用mongoose.Schema.Types.Mixed指定
ObjectId 对象ID,需要使用mongoose.Schema.Types.ObjectId指定
Decimal128 高精度数字,需要使用mongoose.Schema.Types.Decimal128指定

字段值验证

Mongoose有一些内置验证器,可以对字段值进行验证。

必填项

title: {
		type: String,
		required: true // 设置必填项
}

默认值

author: {
		type: String,
		default: '匿名' // 设置默认值
}

枚举值

gender: {
		type: String,
		enum: ['男', '女'] // 设置的值必须是数组中的
}

唯一值

username: {
		type: String,
		unique: true // 字段值必须唯一
}

unique需要重建集合才能有效果

posted @ 2023-12-02 13:56  前端cry  阅读(84)  评论(0编辑  收藏  举报