我正在尝试使用 mongoose 和 node 在 mongodb 中存储一组对象,并进行简单的验证,但使用起来非常困难
我正在定义一个架构和一个自定义验证函数,如下所示:
const mongoose = require("mongoose");
const fieldsSchema = mongoose.Schema({
title: {
type: String,
minlength: 2,
maxlength: 250,
},
list: {
type: Array,
primaryText: {
type: String,
minlength: 1,
maxlength: 250,
},
secondaryText: {
type: String,
minlength: 2,
maxlength: 250,
},
listType: {
type: String,
enum: ["listOne", "listTwo"],
minlength: 2,
maxlength: 250,
},
items: {
required: isListTypeTwo,
type: Array,
itemTitle: {
type: String,
minlength: 2,
maxlength: 250,
},
itemContent: {
type: String,
minlength: 2,
maxlength: 250,
},
},
},
});
function isListTypeTwo() {
if (this.listType === "listTwo") return true;
return false;
}
const Field = new mongoose.model("Field", fieldsSchema);
exports.fieldsSchema = fieldsSchema;
exports.Field = Field;
然后我像这样创建一个邮政路线:
const { Field } = require("../models/field");
const express = require("express");
const router = express.Router();
router.post("/", async (req, res, next) => {
let field = new Field({
title: req.body.title,
list: req.body.list,
});
field = await field.save();
res.send(field);
});
module.exports = router;
我像这样通过邮递员传递我的 JSON 数据:
{
"title": "title",
"list": [
{
"primaryText": "primaryText",
"secondaryText": "secondaryText",
"listType": "listOne"
},
{
"primaryText": "primaryText",
"secondaryText": "secondaryText",
"listType": "listTwo"
}
]
}
现在,这里有一些我无法解决的问题,请求您的帮助:
如何将正确定义的数组结构传递给我的路由,而不是说:
list: req.body.list
,还有更详细的内容(但无需手动访问每个对象,当然,例如 ~[0]、~[1] 等)?
为什么我的验证不起作用?
也许我应该以其他方式/结构传递 JSON?
答案 0 :(得分:0)
首先,您需要 body-parser 中间件来正确解析 JSON。
const express = require("express");
const bodyParser = require("body-parser");
const app = express(); // no need to call Router()
// parse application/json
app.use(bodyParser.json())
app.post("/", async (req, res) => {
// your stuff...
});
<块引用>
如何将正确定义的数组结构传递给我的路由,因此可以说,而不是:列表:req.body.list,更详细的内容(但无需手动访问每个对象,当然,例如 ~[0 ]、~1 等)?
不确定我是否理解正确,但也许您只需要一个循环来保存您的字段?
const promises = req.body.list.map(async (item) => { // map loop which will return array of promises
const field = new Field({
title: req.body.title,
item,
});
return field.save(); // returning the promise
});
res.send(Promise.all(promises));
此外,添加 try/catch 块以捕获并记录 mongoose 架构上的任何可能错误:
try {
const field = new Field({
title: req.body.title,
item,
});
field.save();
// success
} catch (error) {
console.error(error);
}