nodejs使用MongoDB基本增删改查

本文共有2977个字,页面加载耗时0.001秒,关键词:

基本条件:安装并运行了MongoDB

学习一门后端语言,操作数据库必备增删改查基础。

1.创建连接数据库的公共连接文件

/*conn.js*/
//引入mongoose模块操作数据库
const mongoose = require('mongoose');
//创建数据库连接
mongoose.connect('mongodb://localhost/shop', {
        useUnifiedTopology: true
    })
    .then(res => console.log('数据库连接成功。'))
    .catch(err => console.log('数据库连接失败。'));

//创建集合规则
const goodsSchema = new mongoose.Schema({
    id: Number,
    name: String,
    price: Number,
    amount: Number,
    size: [String]
});

//使用规则集合
const Goods = mongoose.model('Goods', goodsSchema);

//暴露Goods给引用者
module.exports = Goods;

2.添加数据

/*create.js*/
const Goods = require('./conn.js');

//在数据库中添加一些货物

/* 2.1 通过save方法添加 */
//创建文档
const goods = new Goods({
        id: 1,
        name: 'iPhone11',
        price: 6000,
        amount: 888,
        size: ['64G', '128G']
    })
    //保存文档到数据库中
goods.save().then(res => console.log(res)); //返回插入的数据本体

/* 2.2 通过create方法来添加 */
Goods.create({
    id: 2,
    name: 'iPhone11 Pro',
    price: 9000,
    amount: 666,
    size: ['64G', '128G', '256G']
}).then(res => console.log(res)); //返回插入的数据本体

3.查询数据

const Goods = require('./conn.js');

//3.1 查询所有数据
Goods.find()
    .then(res => console.log(res)); //返回的是一个数组

//3.2 传入指定条件查找(多个符合)
Goods.find({ price: 9000 })
    .then(res => console.log(res)); //数组

//3.3 findOne方法返回一条文档 默认返回当前集合中的第一条文档
Goods.findOne({ name: 'iPhone11' })
    .then(result => console.log(result)); //返回一个对象

//3.4 查询价格字段大于2000并且小于6000的文档
Goods.find({ price: { $gt: 2000, $lt: 6000 } })
    .then(result => console.log(result));

//3.5 查询size字段值包含256G的文档
Goods.find({ size: { $in: ['256G'] } })
    .then(result => console.log(result));

//3.6 选择要查询的字段
Goods.find()
    .select('name price -_id') //-为屏蔽某个字段
    .then(result => console.log(result));

//3.7 根据价格字段进行升序排列
Goods.find()
    .sort('price')
    .then(result => console.log(result));

//3.8 根据库存字段进行降序排列
Goods.find().sort('-amount')
    .then(result => console.log(result));

//3.9 查询文档跳过前一条结果 限制显示2条结果
Goods.find()
    .skip(1)
    .limit(2)
    .then(result => console.log(result));

4.更新数据

/* update.js */
const Goods = require('./conn.js');

//4.1 如果匹配了多条文档, 只会更新匹配成功的第一条文档
Goods.updateOne({ name: 'iPhone11' }, { amount: 500, price: 5999 })
//     .then(result => console.log(result)); //{ n: 1, nModified: 1, ok: 1 }

//4.2 全部修改
Goods.updateMany({}, { amount: 1000 })
    .then(result => console.log(result)); //{ n: 4, nModified: 4, ok: 1 }

5.删除数据

const Goods = require('./conn.js');

// 如果查询条件匹配了多个文档 那么将会删除第一个匹配的文档
Goods.findOneAndDelete({ name: 'iPhone11' })
    .then(result => console.log(result)); // 返回删除的文档

// 删除多条,若参数为空,则删库
Goods.deleteMany({})
    .then(result => console.log(result)); //{ n: 3, ok: 1, deletedCount: 3 }

扫码在手机查看