(Nodejs,expressjs,mongodb)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性'username'>>

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

我正在尝试从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

我正在尝试从mongodb中为客户打印帖子的作者,但是很遗憾,我的代码抛出错误。用全栈javascript编写的代码,我进行了一些搜索以找出问题所在...

javascript node.js mongodb express
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.