node.js - 从 Mongoose 的文档中检索数组元素
问题描述
我有一个接受路由参数的端点。forms 路由接受 route 参数并使用该参数使用 Mongoose 在 Forms 集合中查找相应的表单。但是,当我检索文档时,返回的“字段”属性(它是一个数组)没有包含在数组中的任何元素。
表单集合的架构如下:
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);
}
});
推荐阅读
- java - Spring Cache - @CachePut 和 @CacheEvict 之间的真正区别
- c++ - 引用没有 glGetUniformLocation 的制服
- r - 有没有一种方法可以在将 noUiSliderInput 启动为 null 时更新两个值的值?
- angular - 访问在 Angular 8 中显示我的控制台的资源
- javascript - 如何在 javascript 中更改 json obj 的一部分?
- python - 如何使用 Python(或 Perl)检测“暗”图像边框并裁剪到它?
- javascript - Gatsby 404 页面在生产中无法正常工作
- linux - 当我尝试运行 BigBlueButton 时得到“java.io.IOException: error=24, Too many open files”
- c# - 调试从 C# 调用的 python 脚本
- ffmpeg - ffmpeg RTP 音频组播流断断续续