Mongoose查增改删

  • src目录下新建一个文件夹models,用来存放数据模型和操作数据库的方法。
  • models目录下新建一个文件user.js,用来管理用户信息相关的数据库操作。
  • 相关的数据模型和数据库操作方法,最后通过module.exports暴露出去。

mongoose版本8.0.0

1-创建结构

const mongoose = require("mongoose");
const userSchema = new mongoose.Schema(
    {
        id: {
            type: Number,
            index: true,
            unique: true,
        },
        name: String,
    },
    {
        versionKey: false, // 设置false,存取数据就不会带版本id
    }
);

2-创建模型

const User = mongoose.model("user", userSchema);

3-查增改删

批量查询Model.find()

Model.find(filter [, projection] [, options])

await User.find({ name: 'kaka' }, 'name phone'); // 字段前加'-'表示不返回的字段
await User.find({}, { name: 1, phone: 1 }); // 1-要返回的字段 0-不返回的字段

可以包在函数里,最后通过module.exports把函数暴露出去。

// 查
function FindUserList() {
    return User.find();
}

单个查询Model.findOne()

Model.findOne([conditions] [, projection] [, options])

await User.findOne({ id: 1 }, { name: 1, id: 1 });

新增文档Model.create()

Model.create(docs [, options])

await User.create({ name: 'gaga' });
await User.create([{ name: 'mama' }, { name: 'nana' }]);

修改文档Model.findOneAndUpdate()

Model.findOneAndUpdate([conditions] [, update] [, options])

const options = {
    new: true,
    strict: true,
};
await User.findOneAndUpdate({ id: 1 }, { id: 1, name: 'newName' }, options);
  • conditions:查询条件。
  • update:新的文档。
  • options:配置项,参见Model - Mongoose 中文网 (nodejs.cn)
    • options.strict:覆盖模式的严格模式选项(默认启用),可确保传递给模型构造函数的、结构中未指定的值不会保存到数据库中。
    • options.upsert:默认为false。如果为true,并且没有找到文档,则插入新文档。
    • options.projection:可选字段返回。
    • options.new:默认为false。如果为true,则返回修改后的文档,而不是原始文档。

删除文档Model.findOneAndDelete()

Model.findOneAndDelete(conditions [, options])

await User.findOneAndDelete({ id: 1 });

完整代码

// src/models/user.js

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema(
    {
        id: {
            type: Number,
            index: true,
            unique: true,
        },
        name: String,
    },
    {
        versionKey: false,
    }
);

const User = mongoose.model("user", userSchema);

// 查-列表
function FindUserList() {
    return User.find();
}

// 查
function FindUser(id) {
    return User.findOne({ id });
}

// 改
function UpdateUser(id, update) {
    const options = {
        new: true,
        strict: true,
    };
    return User.findOneAndUpdate({ id }, update, options);
}

// 增
function AddUser(user) {
    return User.create(user);
}

// 删
function DeleteUser(id) {
    return User.findOneAndDelete({ id });
}

module.exports = {
    User,
    FindUserList,
    FindUser,
    UpdateUser,
    AddUser,
    DeleteUser,
};
posted @ 2023-12-02 21:00  前端cry  阅读(72)  评论(0编辑  收藏  举报