无法使用 mongoose 访问对象的属性

问题描述 投票:0回答:1

样本数据:

{ "_id": "ObjectId_for_Site1", "name": "Site 1", "address": "123 Reeganangam", "manager": { "_id": "ObjectId_for_Manager1", "name": "Karthik", "type": "Manager" } }

控制器

const getAllSites = async (req, res) => {
  try {
    const sites = await Site.find();
    console.log(sites);
    res.status(200).json(sites);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

架构:

const managerSchema = new Schema({
\_id: mongoose.Schema.Types.ObjectId,
name: String,
type: String,
});

const siteSchema = new Schema({
\_id: mongoose.Schema.Types.ObjectId,
name: String,
address: String,
manager: managerSchema,
});

const Site = mongoose.model('Site', siteSchema, 'Site_Collection');

控制器引用位置:


router.get('/', async (req, res) =\> {
try {
const sites = await siteController.getAllSites();

    if (sites && Array.isArray(sites)) {
      const siteNames = sites.map((site) => site.name);
      res.render('main', {
        profile_picture_url: '[https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing](https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing)',
        username: 'Sundar',
        sites: siteNames,
      });
    } else {
      res.status(500).json({ error: 'Failed to fetch sites data' });
    }

} catch (error) {
res.status(500).json({ error: error.message });
}
});

注意:无法使用猫鼬访问对象的属性。我能够通过 http:localhost:3000/api/site 获得响应,但不能通过 http:localhost:3000/main 获得响应。相反,我收到此错误: {“错误”:“无法读取未定义的属性(读取'状态')”}

node.js mongodb express mongoose pug
1个回答
0
投票

我不确定我的答案,因为我无法运行代码。 但正如我所看到的,您已经在

getAllSites
控制器内响应了即将到来的请求。 一旦您发送了
response
,请求-响应周期就会关闭,因此这行代码:

const sites = await siteController.getAllSites();

未获得预期并等待的

sites
值,因为
getAllSites
确实关闭了请求-响应周期,它不返回任何值。

我认为你应该重新组织你的代码。 我看不出仅仅为了执行此行而创建整个控制器有任何意义:

const sites = await Site.find();
你可以考虑这样做:(在我看来,它更干净)

router.get('/', getAllSites);

然后将所有代码移至

getAllSites
内部,最后,像您一样从那里发送响应。

或者将你的控制器修改为这样:

const getAllSites = async (req, _, next) => {
try {
const sites = await Site.find();
req.sites = sites; // this is going to include the data to the current request so the next middleware in the stack can access it.
next();
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});


router.get('/', getAllSites, async (req, res) =\> {
try {
const sites = req.sites;

    if (sites && Array.isArray(sites)) {
      res.render('main', {
        profile_picture_url: '[https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing](https://drive.google.com/file/d/1fhSUOv08fdHzl7r98Hy8_MAGVt3N7loL/view?usp=sharing)',
        username: 'Sundar',
        sites: siteNames,
      });
    } else {
      res.status(500).json({ error: 'Failed to fetch sites data' });
    }

} catch (error) {
res.status(500).json({ error: error.message });
}
});

希望我的回答可以对您和其他人有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.