使用Node+MongoDB来进行前后端交互开发(使用Node创建轻量级服务器,使用MongoDB存储数据)

本文讲解使用Node+MongoDB实现前后端交互开发

 

话不多说,直接上码

const mongoService = require('mongoose');

var testMongodbService = {
    connect: function(success) {
        // 这里只管连接,如果没有这个数据库,会自动创建
        mongoService.connect('mongodb://localhost/lingbug', { useUnifiedTopology: true, useNewUrlParser: true }).then(() => {
            console.log('mongoDB连接成功!');
            if (success) {
                success();
            }
        }).catch((error) => {
            console.log('连接mongoDB失败!');
            console.log(error);
        });
    },
    createTable: function(name, schema) {
        var schemaInfo = new mongoService.Schema(schema);
        var table = mongoService.model(name, schemaInfo);
        testMongodbService.table[name] = table;
    },
    table: {},
    addData1: function(tableName, data) {
        // 通过构造函数新增
        var table = testMongodbService.table[tableName];
        var dataInfo = new table(data);
        dataInfo.save();
        console.log('保存成功!');
    },
    addData2: function(tableName, data) {
        var table = testMongodbService.table[tableName];

        // 通过回调新增
        // table.create(data, (error, result) => {
        //     if (error) {
        //         console.log('保存失败!');
        //         console.log(error);
        //     } else {
        //         console.log('保存成功!');
        //         console.log(result);
        //     }
        // });

        // 另一种方式,使用promise,一般都是这样新增
        table.create(data).then(result => {
            console.log('保存成功!');
            console.log(result);
        }).catch(error => {
            console.log('保存失败!');
            console.log(error);

            // 如果校验不通过,如何获取到提示信息呢?
            // 如下:
            var errorModel = error.errors;
            for (var field in errorModel) {
                var errorItem = errorModel[field];
                var errorItemMsg = errorItem.message;
                console.log(errorItemMsg);
            }
        });
    },
    findCallback: function(result) {
        if (result instanceof Array) {
            console.log('查询到' + result.length + '条数据:');
        }
        console.log(result);
    },
    initUserData: function() {
        var nameStr = 'Ling、bug,薇恩,上官婉儿,王昭君,露娜';
        var ageStr = '24,23,40,30,70';
        var accountStr = 'lingbug,vn,shangguanwaner,wangzhaojun,luna';
        var hobbyStr = '写代码,研究技术;看电视,做饭,拍照;毛笔写字,秀操作;冰冻敌人,大招封路;秀操作,飘逸,月下无限连';

        var names = nameStr.split(',');
        var accounts = accountStr.split(',');
        var ages = ageStr.split(',');
        var hobbys = hobbyStr.split(';');
        for (let index = 0; index < names.length; index++) {
            testMongodbService.addData2('UserInfo', {
                userId: '100' + index,
                userName: names[index],
                account: accounts[index],
                password: accounts[index],
                age: ages[index],
                hobby: hobbys[index].split(','),
                status: index % 2 == 0
            });
        }
    },
    testFind: function() {
        // 这里只做查询多条数据示范,findOne一样,只不过结果是只返回第一条
        var table = testMongodbService.table['UserInfo'];

        // 等于查询
        table.find({ userName: '上官婉儿' }).then(testMongodbService.findCallback);

        // 要想查找范围数据:{$gt:20,$lt:50}意思是查询大于20小于50的这个范围的数据
        table.find({ age: { $gt: 18, $lt: 25 } }).then(testMongodbService.findCallback);

        // in查询
        table.find({ hobby: { $in: ['秀操作'] } }).then(testMongodbService.findCallback);

        // 只查询指定字段, 字段名使用空格隔开, 不想查哪个字段, 字段前面加-
        table.find().select('userName age -_id').then(testMongodbService.findCallback);

        // 排序查询: 升序直接输入字段名, 降序加-
        // 根据年龄升序查询
        table.find().sort('age').then(testMongodbService.findCallback);
        // 根据年龄降序查询
        table.find().sort('-age').then(testMongodbService.findCallback);

        // 分页查询: 跳过第一条, 查询两条
        table.find().skip(1).limit(2).then(testMongodbService.findCallback);

        var articleTable = testMongodbService.table['Article'];

        // 关联查询(要在表结构就要指定关键关系,新增数据要将关联关系添加进去)
        // 查询文章信息,以及作者信息(存储的是用户id,这里通过关联查询,查询出作者的详细信息)
        articleTable.find().populate('author').then(testMongodbService.findCallback);
    },
    testDelete: function() {
        var table = testMongodbService.table['UserInfo'];

        // 查找到一条数据并且删除,如果查询结果是多条,则会删除第一条
        table.findOneAndDelete({ _id: '5e9adaafb814ba1ba4930ab0' }).then(result => {
            console.log(result);
        });

        // 删除多条符合条件的数据,如果不传递where,则会删除所有数据(慎重操作)
        table.deleteMany({}).then(result => {
            var { ok, n: count } = result;
            if (ok == '1') {
                console.log('成功删除' + count + '条数据!');
            } else {
                console.log('删除失败!');
            }
        });
    },
    createUserTableNormal: function() {
        // 常规创建表,如果不存在系统会自动创建
        testMongodbService.createTable('UserInfo', {
            userId: String,
            userName: String,
            account: String,
            password: String,
            age: Number,
            hobby: Array,
            status: Boolean
        });
    },
    createUserTableWithValidate: function() {
        // 创建表时增加校验,操作mongo异常时,如何获取到校验信息,请上滑查看新增
        testMongodbService.createTable('Article', {
            title: {
                type: String,
                required: [true, '文章标题不能为空!'], //必填
                minlength: 2, //最小长度,都可以像上面一样设置自定义提示信息,传入数组即可
                maxlength: 30, //最大长度
                trim: true, //在操作数据之前,是否需要去除两边的空格
            },
            readCount: {
                type: Number,
                min: 0, //最小值
                max: 999999, //最大值
            },
            publishDate: {
                type: Date,
                default: Date.now, //默认值:当前时间
            },
            category: {
                type: String,
                enum: ['java', 'c#', 'javascript', 'node'], //限制数据只能在这个枚举中,其他的不允许
            },
            author: {
                // 表之间的关联:作者字段跟用户表的_id关联起来
                type: mongoService.Schema.Types.ObjectId,
                ref: 'UserInfo',
                //自定义校验规则
                validate: {
                    validator: function(value) {
                        // 返回true校验通过,false不通过
                        return value && (value + '').length <= 100;
                    },
                    message: '作者不能为空并且长度不能超过100'
                }
            }
        });
    },
    testUpdate: function() {
        var table = testMongodbService.table['UserInfo'];

        // 修改单条,如果查询到多个,只会修改第一个
        // 将userId为1000的名称修改为吕布
        table.updateOne({ userId: '1000' }, { userName: '吕布' }).then(result => console.log(result));

        // 修改多个
        // 将所有数据的年龄修改为18岁
        table.updateMany({}, { age: 18 }).then(result => console.log(result));
    },
    initArticleData: function() {
        var userTable = testMongodbService.table['UserInfo'];
        userTable.find().select('_id').then(userList => {
            var userIds = userList.map(r => r._id);
            for (let i = 0; i < userIds.length; i++) {
                var userId = userIds[i];
                var articleItem = {
                    title: '文章' + i,
                    readCount: 0,
                    category: 'node',
                    author: userId
                };
                console.log(articleItem);
                testMongodbService.addData2('Article', articleItem);
            }
        });
    },
    run: function() {
        // 给mongodb导入数据命令(要给mongodb的bin文件夹配置环境变量):
        // mongoimport -d 数据库名称 -c 表(集合)名称 --file 要导入的文件路径
        testMongodbService.connect(() => {
            // 常规创建表
            testMongodbService.createUserTableNormal();

            // 创建带校验的表
            testMongodbService.createUserTableWithValidate();

            // 增
            testMongodbService.initUserData();
            testMongodbService.initArticleData();

            // 查
            testMongodbService.testFind();

            // 删
            testMongodbService.testDelete();

            // 改
            testMongodbService.testUpdate();

        });
    }
};

testMongodbService.run();

 

总结:

1.实现了使用Node来实现对MongoDB的增删改查操作,第三方模块使用的是mongoose

2.创建表结构:a.常规创建(字段名称,字段类型);b.创建可以校验的表(使用自带的校验以及自定义校验)

3.查询相关api:
a.查询集合:find
b.查询单条:findOne
c.查询条件:在find内使用对象传递
    等于:{field:value}
    大于:{$gt:value}
    小于:{$lt:value}
    in:{$in:array}
d.排序:sort
    正序:field
    倒叙:-field
e.分页:skip,limit
f.连表查询:populate(注意:需要在构建表时指定关联关系)

4.删除相关api:
a.查询出来一条然后删除:findOneAndDelete
b.删除多条:deleteMany

5.修改相关api:
a.修改单条:updateOne
b.修改多条:updateMany

6.新增相关api:
a.通过构造函数新增
b.通过create方法来新增

 

Ending~

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值