Vue project configures MongoDB's addition, deletion, modification and query operations

To configure MongoDB's add, delete, modify, and query operations in Vue, you need to install the `mongoose` module first to connect to the MongoDB database.

1. In the root directory of the Vue project, use the command line to install the `mongoose` module:

        npm install mongoose --save

2. Find the app.js file that starts node (I am in the server file, which is the server file mentioned in the third step)

const express = require('express')
const app = express()
const mongoose = require('mongoose');
var config = require('./config');//引入config中mongoDB地址

// 解析 url-encoded格式的表单数据
app.use(express.urlencoded({ extended: false }));
 
// 解析json格式的表单数据
app.use(express.json());

var article=require('./routes/article');
app.use('/article', article);

var db=mongoose.connect(config.db.path, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
db.then(function (data) {
  console.log('--数据库连接成功--');

}).catch(function (error) {
  console.log('数据库连接失败: ' + error);
});

module.exports = app

In the above code, `mongoose.connect` is used to connect to the MongoDB database 

My config.db.path here is configured by address. You can also write the address directly into it.

const url = 'mongodb://localhost:27017/mydatabase';
var db=mongoose.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})

3. Create a new server file in the root directory of the Vue project, create a new file config under the server file, and create a new db.js file in config.

const mongoose = require('mongoose');
let Promise = require('bluebird');

// 定义数据模型
const ArticleSchema = new mongoose.Schema({
    article_title:String, //标题
    article_desc:String,    //简介
    article_info:String,    //内容
    createdAt: { //创建日期
        type: Date,
        default: Date.now
    }

});
//mongoose.model三个参数分别代表模型的名称、模型的Schema、模型的集合名称
const ArticleModel = mongoose.model('Article', ArticleSchema);
Promise.promisifyAll(ArticleModel);
Promise.promisifyAll(ArticleModel.prototype);
module.exports = ArticleModel

mongoose.connection` is used to obtain the database connection object. Then, use `mongoose.Schema` to define the data model of the Article, and use `mongoose.model` to create the Article model. (The data model here is the field of your page data).

4. Create new article.js in the server>routes file

var express = require('express');
var articleRouter = express.Router();
var ArticleModel = require('../db');
//查询
articleRouter.get('/:id', (req, res) => {
    const articleId = req.params.id;
    if (!articleId) {
        return {
            err_code: -2,
            err_msg: 'no id'
        };
    }
    ArticleModel.findOne({_id: articleId}).then(response => {
        res.send({
            err_code: 0,
            data: response
        });
    }).catch(err => {
        console.log(err);
        res.send({
            err_code: -1,
            err_msg: 'server error'
        });
    });
});
// 获取列表
articleRouter.get('/', (req, res) => {
    let page = req.query.page,
        size = req.query.size,
        store = req.query.store;

    page = parseInt(page, 10) || 1;
    size = parseInt(size, 10) || 100;

    let skip = (page - 1) * size;
    let sort = '-createAt';
    let data = {};
    Promise.all([
        //Articletype 集合的数据  find 指定的查询条件 sort 排序规则  skip跳过指定数量的记录,用于分页查询  limit 返回的数据为指定的size  exec查询操作并返回记录
        ArticleModel.find(data).sort(sort).skip(skip).limit(size).exec(),
        ArticleModel.count(data)
    ]).then(([data, count]) => {
        res.send({
            data: data,
            total: count,
            err_code: 0
        });
    }).catch(err => {
        console.log(err);
        res.send({
            err_code: -2
        });
    });
});
// 新增列表
articleRouter.post('/', (req, res) => {
    var articleBody=req.body
    let data = {
        article_url: articleBody.article_url
    };
    //先检查是否有已经创建的数据
    ArticleModel.find(articleBody).then(datas => {
        'use strict';
        if (datas.length > 0) {
            res.send({
                err_code: -1,
                err_msg: '资源已存在'
            });
            return;
        }
        ArticleModel.create(articleBody).then(response => {
            res.send({
                err_code: 0,
                err_msg: '保存成功'
            });
        }).catch(res => {
            res.send({
                err_code: -2,
                err_msg: '保存失败'
            });
        });
    });
});
// 删除
articleRouter.delete('/:id', (req, res) => {
    const articleId = req.params.id;
    if (!articleId) {
        return res.send({
            err_code: -1,
            err_msg: '缺少ID'
        });
    }
    //mongoDB已经弃用remove使用deleteOne 删除单个文档或者deleteMany 删除多个文档
    ArticleModel.deleteOne({_id: articleId}).then(response => {
        res.send({
            err_code: 0
        });
    }).catch(err => {
        res.send({
            err_code: -2,
            err_msg: '删除失败'
        });
    });
});
// 修改
articleRouter.put('/', (req, res) => {
    const articleBody = req.body;
    const articleId = req.body.id;
    console.log(req.body)
    if (!articleId) {
        return res.send({
            err_code: -1,
            err_msg: '缺少id'
        });
    }
    ArticleModel.findOneAndUpdate({_id: articleId}, {$set: articleBody}).then(response => {
        res.send({
            err_code: 0,
        });
    }).catch(err => {
        console.log(err);
        res.send({
            err_code: -2,
            err_msg: '数据库错误'
        });
    });
});
module.exports = articleRouter

The most difficult problem to find here is that Mongoose updates will deprecate some methods. For example, if you delete remove, the error ArticleModel.remove is not a function will be reported. Search online for the methods recommended by mongoose. It is more recommended to use `deleteOne` for remove here. or `deleteMany` method, depending on whether you want to delete a single document or multiple documents. You can solve this problem by replacing the `remove` method with `deleteOne` or `deleteMany`. 

5. Call in the page

example:

query list

import axios from 'axios'
dexport default{
    mounted():{
        axios.get('/article', {params}).then(res => {
            console.log(res)//查看是否调用成功
        });
    }
}

delete

axios.delete(`/article/${id}`).then(res=>{
                console.log(res.data)
                if(res.data.err_code==0){
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                    this.initList()
                }else{
                    this.$message({
                        type: 'error',
                        message: res.data.err_msg
                    });
                }
            })

6. This error may be reported when requesting the interface.

Database access permissions are set for MongoDB , so whether you open mongodb or connect and remove the account and password, a database error will be displayed. Therefore, whether you run node app.js, you need permissions to successfully use it.

Add the user name and password root:root in front of the database connection, and add authSource=admin after it to perform login authentication through the admin library.

mongodb://admin:123@localhost:27017/mydatabase?authSource=admin '

As shown below:

Guess you like

Origin blog.csdn.net/weixin_57163112/article/details/132673279