简体   繁体   English

发行迭代对象的MongoDB数组

[英]Issue Iterating MongoDB Array of Objects

I just can't figure out what's wrong with this. 我只是不知道这是怎么回事。 Does anyone know why I get this error? 有谁知道为什么我会收到此错误? I'm using Node, Express, MongoDB with Mongoose. 我正在使用Node,Express,MongoDB和Mongoose。

Here's the code, the console.log() lines are just to debug and they are what throw the error. 这是代码, console.log()行仅用于调试,它们是引发错误的原因。

// report view
app.get("/report", isLoggedIn, function(req, res){
    User.findById(req.user._id, function(err, foundUser){
        if(err){
            console.log(err);
            console.log(foundUser);
        } else {
            console.log(foundUser);
            console.log();
            console.log(foundUser.purchases[0].phrase);
            res.render("report.ejs", {user:foundUser});
        }
    });
});

Here's the user document in MongoDB: 这是MongoDB中的user文档:

{
    "_id" : ObjectId("59d4dc48fba3ef12437bf4b1"),
    "salt" : "30dd9c9942...",
    "hash" : "8c8c96d88a708...",
    "username" : "Christian Lewis",
    "email" : "email@email.com",
    "signupDate" : ISODate("2017-10-04T13:04:08.167Z"),
    "__v" : 6,
    "purchases" : [
        {
            "phrase" : "Porche 918 Spyder",
            "location" : "South Yarra"
        },
        {
            "phrase" : "Blinds",
            "location" : "United Kingdom"
        }
    ]
}

And here's everything that comes out of the console: 以下是控制台中的所有内容:

{ _id: 59d4dc48fba3ef12437bf4b1,
  username: 'Christian Lewis',
  email: 'christianllewis@gmail.com',
  __v: 6,
  signupDate: 2017-10-04T13:04:08.167Z,
  purchases:
   [ { location: 'South Yarra', phrase: 'Porche 918 Spyder' },
     { location: 'United Kingdom', phrase: 'Blinds' } ] }

events.js:160
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'phrase' of undefined
    at /Volumes/Store/Lickety-Split/website/app.js:58:47
    at Query.<anonymous> (/Volumes/Store/Lickety-Split/website/node_modules/mongoose/lib/model.js:3841:16)
    at /Volumes/Store/Lickety-Split/website/node_modules/kareem/index.js:273:21
    at /Volumes/Store/Lickety-Split/website/node_modules/kareem/index.js:131:16
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

I can't find an answer to this, I can't spot the error, so I apologise if this is a duplicate question. 我找不到答案,找不到错误,因此如果这是一个重复的问题,我深表歉意。 And thank you for any help. 并感谢您的任何帮助。

The error is happening on this line 该行发生错误

console.log(foundUser.purchases[0].phrase);

This would suggest foundUser.purchases array is empty, however based on your data logged, it is not. 这将建议foundUser.purchases数组为空,但是根据记录的数据,它不是。

Can you confirm that that the data posted is in fact the correct log information. 您可以确认发布的数据实际上是正确的日志信息吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM