Vue で MongoDB の追加、削除、変更、クエリ操作を設定するには、まず `mongoose` モジュールをインストールして MongoDB データベースに接続する必要があります。
1. Vue プロジェクトのルート ディレクトリで、コマンド ラインを使用して `mongoose` モジュールをインストールします。
npm install mongoose --save
2. ノードを起動する app.js ファイルを見つけます (私はサーバー ファイルにいます。これは 3 番目の手順で説明したサーバー ファイルです)。
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
上記のコードでは、「mongoose.connect」を使用して MongoDB データベースに接続しています。
ここの config.db.path はアドレスによって構成されており、アドレスを直接書き込むこともできます。
const url = 'mongodb://localhost:27017/mydatabase';
var db=mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
3. Vue プロジェクトのルート ディレクトリに新しいサーバー ファイルを作成し、サーバー ファイルの下に新しいファイル config を作成し、config 内に新しい db.js ファイルを作成します。
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` はデータベース接続オブジェクトを取得するために使用されます。次に、`mongoose.Schema` を使用して Article のデータ モデルを定義し、`mongoose.model` を使用して Article モデルを作成します。(ここでのデータ モデルはページ データのフィールドです)。
4.server>routesファイルに新しいarticle.jsを作成します
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
ここで見つけるのが最も難しい問題は、Mongoose の更新により一部のメソッドが非推奨になることです。たとえば、remove を削除すると、ArticleModel.remove is not a function というエラーが報告されます。mongoose が推奨するメソッドをオンラインで検索してください。より推奨されます。単一のドキュメントを削除するか複数のドキュメントを削除するかに応じて、ここで削除するには `deleteOne` メソッドを使用するか、または `deleteMany` メソッドを使用します。この問題は、「remove」メソッドを「deleteOne」または「deleteMany」に置き換えることで解決できます。
5. ページ内で呼び出します
例:
クエリリスト
import axios from 'axios'
dexport default{
mounted():{
axios.get('/article', {params}).then(res => {
console.log(res)//查看是否调用成功
});
}
}
消去
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. このエラーは、インターフェイスを要求するときに報告される場合があります。
MongoDBにはデータベースのアクセス権限が設定されているため、 mongodb を開いても、接続してアカウントとパスワードを削除しても、データベース エラーが表示されるため、node app.js を実行する場合でも、正常に使用するには権限が必要です。
データベース接続の前にユーザー名とパスワード root:root を追加し、その後に authSource=admin を追加して、管理ライブラリを通じてログイン認証を実行します。
mongodb://admin:123@localhost:27017/mydatabase?authSource=admin '
以下に示すように: