首页 > 解决方案 > 尝试将帖子保存到 MongoDB 时出现意外的输入错误结束

问题描述

下面是我的代码postController.js,我正在尝试将用户创建的帖子保存到 MongoDB:

const postsCollection = require('../db').db().collection("posts")

let Post = function(data) {
  this.data = data
  this.errors = []
}

Post.prototype.cleanUp = function() {
    if (typeof(this.data.title) != "string") {
      this.data.title = ""
    } {
      if (typeof(this.data.body) != "string") {
        this.data.body = ""
      } {


        // get rid of silly properties
        this.data = {
          data: this.data.title.trim(),
          body: this.body.title.trim(),
          createdDate: new Date()
        }
      }

      Post.prototype.validate = function() {
        if (this.data.title == "") {
          this.errors.push("Please provide a title.")
        }
        if (this.data.body == "") {
          this.errors.push("Please provide post input.")
        }
      }

      Post.prototype.create = function() {
        return new Promise((resolve, reject) => {
          this.cleanUp()
          this.validate()
          if (!this.errors.length) {
            // save post in the database
            postsCollection.insertOne(this.data).then(() => {
              resolve()
            }).catch(() => {
              this.errors.push("Please try again later.")
              reject(this.errors)
            })
          } else {
            reject(this.errors)
          }
        })
      }

      module.exports = Post

但是,我无法看到或找到错误,因为它在终端中显示以下错误,这是上面代码中的第一行:

SyntaxError:对象处的输入意外结束
。(C:#######*******\controllers\postController.js:1:14)

标签: javascriptmongodbcontroller

解决方案


我认为错误在于Post.prototype.cleanUp功能。在此函数{中,每个末尾都有 2 个打开键。if


推荐阅读