繁体   English   中英

(Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“用户名”

[英](Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined

我正在尝试从 mongodb 为客户端打印帖子的作者,但不幸的是我的代码抛出错误。 代码是用全栈 javascript 编写的,我已经做了一些搜索以找出代码有什么问题,但我没有找到答案,所以如果有人可以帮助我我的代码有什么问题。 谢谢

const postsCollection = require("../db")
  .db()
  .collection("posts")
const ObjectID = require("mongodb").ObjectID
const User = require("./User")
let Post = function (data, userid) {
  this.data = data
  this.errors = []
  this.userid = userid
}
Post.prototype.cleanUp = function () {
  if (typeof this.data.title != "string") {
    this.data.title = ""
  } else if (typeof this.data.body != "string") {
    this.data.body = ""
  }
  // get rid of any bogus properties
  this.data = {
    title: this.data.title.trim(),
    body: this.data.body.trim(),
    createdDate: new Date(),
    author: ObjectID(this.userid)
  }
}
Post.prototype.validate = function () {
  if (this.data.title == "") {
    this.errors.push("You must provide a title")
  } else if (this.data.body == "") {
    this.errors.push("You must provide post content")
  }
}
Post.prototype.create = function () {
  return new Promise((resolve, reject) => {
    this.cleanUp()
    this.validate()
    if (!this.errors.length) {
      // save post into database
      postsCollection
        .insertOne(this.data)
        .then(() => {
          resolve()
        })
        .catch(() => {
          this.errors.push("Please try again later.")
          reject(this.errors)
        })
    } else {
      reject(this.errors)
    }
  })
}
Post.findSingleById = function (id) {
  return new Promise(async function (resolve, reject) {
    if (typeof id != "string" || !ObjectID.isValid(id)) {
      reject()
      return
    }
    let posts = await postsCollection
      .aggregate([{
          $match: {
            _id: new ObjectID(id)
          }
        },
        {
          $lookup: {
            from: "users",
            localField: "author",
            foreignField: "_id",
            as: "authorDocument"
          }
        },
        {
          $project: {
            title: 1,
            body: 1,
            createdDate: 1,
            author: {
              $arrayElemAt: ["$authorDocument", 0]
            }
          }
        }
      ]).toArray()
    // Clean up author property in each post object
    posts.map(function (post) {
      console.log("[+] something goes wrong")
      post.author = {
        username: post.author.username,
        avatar: new User(post.author, true).avatar
      }
      return post
    })
    if (posts.length) {
      console.log(posts[0])
      resolve(posts[0])
    } else {
      reject()
    }
  })
}
module.exports = Post

发布对象有问题
您的帖子对象没有用户名
请提出一些条件

posts.map(function (post) {
  console.log("[+] something goes wrong")
  post.author = {
    username: post.author && post.author.username, // here
    avatar: new User(post.author, true).avatar
  }
  return post
})

暂无
暂无

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

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