【问题标题】:How to use MongoDB's new Schema Validation feature in Express.js?如何在 Express.js 中使用 MongoDB 的新模式验证功能?
【发布时间】:2020-11-24 17:53:18
【问题描述】:

您如何在 Express 服务器中实现 MongoDB 的模式验证功能? 我正在开发一个简单的待办事项应用程序并决定使用本机 MongoClient 而不是 mongoose,但我仍然想要一个模式.

此处基于 MongoDB 的文档:https://docs.mongodb.com/manual/core/schema-validation/#schema-validation 您可以使用 Schema 创建一个集合,也可以更新一个没有 schema 的现有集合以拥有一个。命令在 mongo shell 中运行,但是如何在 express 中实现呢?

到目前为止,我所做的是创建一个返回架构验证命令并在每个路由上调用它的函数,但我收到一个错误,说 db.runCommand 不是一个函数。

这是我的快递服务器:

const express = require("express");
const MongoClient = require("mongodb").MongoClient;
const ObjectID = require("mongodb").ObjectID;
const dotenv = require('dotenv').config();
const todoRoutes = express.Router();
const cors = require("cors");
const path = require("path");
const port = process.env.PORT || 4000;
const dbName = process.env.DB_NAME;
let db;

const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

MongoClient.connect(process.env.MONGO_URI,{useNewUrlParser: true},(err,client)=>{
    if(err){
        throw err;
        console.log(`Unable to connect to the databse: ${err}`);
    } else {
        db =  client.db(dbName);
        console.log('Connected to the database');
    }
});

/* Schema Validation Function */
const runDbSchemaValidation = function(){
    return db.runCommand( {
        collMod: "todos",
        validator: { $jsonSchema: {
           bsonType: "object",
           required: [ "description", "responsible","priority", "completed" ],
           properties: {
              description: {
                 bsonType: "string",
                 description: "must be a string and is required"
              },
              responsibility: {
                 bsonType: "string",
                 description: "must be a string and is required"
              },
              priority: {
                bsonType: "string",
                description: "must be a string and is required"
             },
             completed: {
                bsonType: "bool",
                description: "must be a either true or false and is required"
             }
           }
        } },
        validationLevel: "strict"
     } );
}

/* Get list of Todos */
todoRoutes.route('/').get((req,res)=>{
    runDbSchemaValidation();
    db.collection("todos").find({}).toArray((err,docs)=>{
        if(err)
            console.log(err);
        else {
            console.log(docs);
            res.json(docs);
        }
    });
});

/* Get Single Todo */
todoRoutes.route('/:id').get((req,res)=>{
    let todoID = req.params.id;
    runDbSchemaValidation();
    db.collection("todos").findOne({_id: ObjectID(todoID)}, (err,docs)=>{
        if(err)
            console.log(err);
        else {
            console.log(docs);
            res.json(docs);
        }
    });
});

/* Create Todo */
todoRoutes.route('/create').post((req,res,next)=>{
    const userInput = req.body;
    runDbSchemaValidation();
    db.collection("todos").insertOne({description:userInput.description,responsible:userInput.responsible,priority:userInput.priority,completed:false},(err,docs)=>{
        if(err)
            console.log(err);
        else{
            res.json(docs);
        }
    });
});

/* Edit todo */
todoRoutes.route('/edit/:id').get((req,res,next)=>{
    let todoID = req.params.id;
    runDbSchemaValidation();
    db.collection("todos").findOne({_id: ObjectID(todoID)},(err,docs)=>{
        if(err)
            console.log(err);
        else {
            console.log(docs);
            res.json(docs);
        }
    });
});

todoRoutes.route('/edit/:id').put((req,res,next)=>{
    const todoID = req.params.id;
    const userInput = req.body;
    runDbSchemaValidation();
    db.collection("todos").updateOne({_id: ObjectID(todoID)},{ $set:{ description: userInput.description, responsible: userInput.responsible, priority: userInput.priority, completed: userInput.completed }},{returnNewDocument:true},(err,docs)=>{
        if(err)
            console.log(err);
        else
            res.json(docs);
        console.log(db.getPrimaryKey(todoID));
    });
});

/* Delete todo */
todoRoutes.route('/:id').delete((req,res,next)=>{
    const todoID = req.params.id;
    runDbSchemaValidation();
    db.collection("todos").deleteOne({_id: ObjectID(todoID)},(err,docs)=>{
        if(err)
            console.log(err)
        else{
            res.json(docs);
        }
    });
});

app.use('/todos',todoRoutes);

app.listen(port,()=>{
    console.log(`Server listening to port ${port}`);
});

我也在初始客户端连接上尝试过,但我得到了同样的错误:

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    当您第一次运行 MongoDB 驱动程序时,您的验证模式将被添加到它。因此,您无需在每次运行查询时都执行验证。您将直接从最初添加的驱动程序验证模式中获得验证响应。同样,您不会明确知道是哪个对象导致了错误。验证响应将更加通用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      相关资源
      最近更新 更多