Mongoose查增改删

世上唯一不能复制的是时间,唯一不能重演的是人生,唯一不劳而获的是年龄。该怎么走,过什么样的生活,全凭自己的选择和努力。人生很贵,请别浪费!与智者为伍,与良善者同行。Mongoose查增改删,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

  • 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,
};

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/275279.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!