[英]Retrieve array elements from document in Mongoose
我有一个接受路由参数的端点。 forms 路由接受路由参数,并使用该参数在 Forms 集合中使用 Mongoose 查找相应的形式。 但是,当我检索文档时,返回的“字段”属性(它是一个数组)没有包含在数组中的任何元素。
表单集合的架构如下:
const FormSchema = new Schema({
name: String,
fields: [
{
name: String,
label: String,
type: String,
validation: { required: Boolean, min: Number, max: Number || null },
},
],
});
mongoose.model("forms", FormSchema);
我的端点看起来像这样:
app.get("/api/forms/:formName", (req, res) => {
const formName = req.params.formName;
Forms.find({name: formName }).then((form) => {
if (form) {
return res.send(form);
}
return res.send({ error: "No form found" });
});
});
当前端返回响应时,“fields”属性只是一个空数组,即使 fields 数组中有元素。
尝试这个:
架构
const Forms = mongoose.model("forms", FormSchema);
使用您自己的路径将其添加到您的端点文件中
const Forms = require('../models/forms');
也许您可以将其用作端点:
app.get('/api/forms/:formName', (req, res, next) => {
try {
const formName = req.params.formName;
const foundForm = await Forms.find({name: formName})
if (!foundForm) return next(new Error('No form found'));
res.status(200).json({
success: true,
data: foundForm
});
} catch (error) {
next(error);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.