MongoDB-JSON模式验证
谁能告诉我在下面的代码中$jsonSchema的位置吗。每次测试post时,我的代码都返回状态(400)success:false 我所要做的就是验证标题和描述是否输入正确MongoDB-JSON模式验证,mongodb,next.js,json-schema-validator,Mongodb,Next.js,Json Schema Validator,谁能告诉我在下面的代码中$jsonSchema的位置吗。每次测试post时,我的代码都返回状态(400)success:false 我所要做的就是验证标题和描述是否输入正确 import { connectToDatabase } from "../../../util/mongodb"; export default async (req, res) => { const { method } = req; const { db } = await conne
import { connectToDatabase } from "../../../util/mongodb";
export default async (req, res) => {
const { method } = req;
const { db } = await connectToDatabase();
switch (method) {
case "GET":
try {
const products = await db.collection("products").find({}).toArray();
res.status(200).json({ success: true, data: products });
} catch (error) {
res.status(400).json({ sucess: false });
}
break;
case "POST":
try {
const product = await db
.collection("products")
.insertOne(req.body)
.runCommand({
collMod: "products",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["title", "description"],
properties: {
title: {
bsonType: "string",
description: "must be a string and is required",
unique: true,
},
description: {
bsonType: "string",
description: "must be a string and is required",
},
},
},
},
});
res.status(201).json({ success: true, data: product });
} catch (error) {
res.status(400).json({ sucess: false });
}
break;
default:
res.status(400).json({ dsucess: false });
break;
}
};
您是否尝试过使用req.body中的值检查您的验证器在插入代码时是否工作正常-在POST请求之外(可能来自
mongo
shell)。老实说,我不明白您的意思。我是个笨蛋,自学成才。你能进一步解释一下吗?