首页 > 其他分享 >Mongoose查增改删

Mongoose查增改删

时间:2023-12-02 21:12:52浏览次数:26  
标签:name 改删 options 查增 User Mongoose Model true id

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

标签:name,改删,options,查增,User,Mongoose,Model,true,id
From: https://www.cnblogs.com/cry0-0/p/17871533.html

相关文章

  • Mongoose介绍
    官网Mongoose.js中文网(mongoosejs.net)基本使用安装最新的是mongoose8.0.0版本,基于Promise,以前的版本是基于回调函数。npmnpmimongooseyarnyarnaddmongoose使用以mongoose8.0.0举例://1-引入mongooseconstmongoose=require("mongoose");//2-连接......
  • mongoose 的使用
    constmongoose=require('mongoose');mongoose.connect('mongodb://admin:[email protected]:27017/GIS?authSource=admin',{useUnifiedTopology:true,useNewUrlParser:true,}).then(......
  • 导出微信支付交易明细证明账单记录修改删除PDF文件
    微信支付交易明细证明有两种修改方式,一种是导出账单到邮箱后再下载PDF账单文件到电脑桌面进行修改。第二种是导出前在后台修改,这种情况较为复杂要根据个人情况而定,暂不做陈述。现在先来说说第一种方式,先下载账单文件然后把PDF转成WORD的方式进行修改,这种方式简单粗暴,相信很多人都......
  • MongoDB and mongoose All In One
    MongoDBandmongooseAllInOneMongoDB$xcode-select--install$brewtapmongodb/brew$brewupdate$brewinstallmongodb-community@7.0ThemongodserverThemongosshardedclusterqueryrouterTheMongoDBShell,mongoshhttps://docs.mongodb.com/ma......
  • 解决hive数据库的修改删除等更新语句问题
    Hive对使用Update功能的表有特定的语法要求,语法要求如下:(1)要执行Update的表中,建表时必须带有buckets(分桶)属性(2)要执行Update的表中,需要指定格式,其余格式目前赞不支持,如:parquet格式,目前只支持ORCFileformat和AcidOutputFormat(3)要执行Update的表中,建表时必......
  • Mongoose基本使用
    Mongoose基本使用MongooseMongoose是一个对象文档模型库,官网Mongoose方便使用代码操作mongodb数据库参考:MongoDB基础入门,MongoDB官网,MongoDB中文网使用示例://1.安装mongoose//npminstallmongoose//2.导入mongooseconstmongoose=require('mongoose');//3.......
  • 修改修改删除空行
     //导入EXCEL时经常出现类似情况//将前四行的内容都复制到第一行usex1,clearlocalkk=0foreachvarofvarlist_all{localkk=`kk'+1localcc=""forvaluesi=1/4{localcc="`cc'"+`var'[`i']}replace`var'=&......
  • Oracle从入门到精通-合并查询、添加修改删除数据
    6Oracle表的管理6.5oracle表的管理-表查询(重点)6.5.5Oracle表复杂查询--合并查询·合并查询有时在实际应用中,为了合并多个select语句的结果,可以使用集合操作符号union,unionall,intersect,minus1)union该操作符用于取得两个结果集的并集,当使用该操作符时,=selectename,sal,j......
  • Mongodb 以及 node.js中使用mongoose操作数据库
    Mongodb以及node.js中使用mongoose操作数据库1、lowdb一个简陋的数据库第三方库,使用JSON文件来保存数据,进行增删改查。在没有数据库或者数据量小到不使用数据库的时候可以使用,了解即可。2、Mongodb是什么?MongoDB是一个基于分布式文件存储的数据库。相比于纯文件管理数据,数......
  • C网络库mongoose
     官方链接:https://github.com/cesanta/mongoose[C++]-网络库mongoose简介_alwaysrun的博客-CSDN博客_c++mongooseMongoose-基于C的Web服务器介绍和使用-百度文库......