向MongoDB保存帖子时遭遇Unexpected end of input错误求助
Hey there, let's break down what's going wrong here. That Unexpected end of input error almost always means you've got unclosed curly braces {} somewhere in your code, and that's exactly what's happening here. Let's walk through the fixes step by step:
1. Fix Unclosed Braces & Extra Brackets in cleanUp()
Looking at your cleanUp method, you've got extra opening braces that don't have matches, and you never closed the function itself. That's the main cause of the syntax error. Here's the corrected version of this method:
Post.prototype.cleanUp = function() { // Validate title is a string if (typeof(this.data.title) !== "string") { this.data.title = "" } // Validate body is a string (you had an extra opening brace here before) if (typeof(this.data.body) !== "string") { this.data.body = "" } // Clean up and restructure the data object this.data = { title: this.data.title.trim(), // Fixed key name and property reference body: this.data.body.trim(), // Fixed incorrect property path createdDate: new Date() } } // <-- You were missing this closing brace for the cleanUp function!
2. Fix Critical Data Property Typos
In your original cleanUp method, you had two typos that would have broken your data even if the syntax error was fixed:
- You used
data: this.data.title.trim()instead oftitle: this.data.title.trim()— the key name should match the property you intend to store - You wrote
body: this.body.title.trim()which is completely wrong — it should bethis.data.body.trim()(you need to access thebodyproperty from the instance'sdataobject)
3. Full Corrected Code
Here's the complete, working version of your postController.js with all fixes applied, plus a minor best practice update (using strict equality checks):
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 = "" } // Restructure cleaned data with correct properties this.data = { title: this.data.title.trim(), body: this.data.body.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) { postsCollection.insertOne(this.data) .then(() => resolve()) .catch(() => { this.errors.push("Please try again later.") reject(this.errors) }) } else { reject(this.errors) } }) } module.exports = Post
Quick Pro Tip
Consistent indentation (I used 2 spaces here) makes it way easier to spot unclosed braces and typos in the future. It's a small habit that saves a ton of debugging time!
内容的提问来源于stack exchange,提问作者Bit

