首页 > 解决方案 > 从 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 数组中有元素。

标签: node.jsmongodbexpressmongoose

解决方案


尝试这个:

架构

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);
    }
});

推荐阅读