Reputation: 5914
I am trying to save my string to a comma separated array, but when I try to use the JSON.parse
method, I receive this error upon sending a post method and trying to save a record:
SyntaxError: Unexpected token c
at Object.parse (native)
at router.route.post.get.res.render.blogpost (/Users/user/Desktop/Projects/node/blog/app/routes.js:106:34)
Here is my route (error coming at blogpost.save):
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.featureImage = req.body.featureImage; // set the blog image
blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = JSON.parse(req.body.tags.split(",")); // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(isLoggedIn, function(req, res, blogpost) {
res.render('pages/blogpost-create', {
blogpost : blogpost
});
});
Upvotes: 1
Views: 4125
Reputation: 318182
JSON.parse
parses a string (of valid JSON) into an object/array.
You already have an array, as you're doing
req.body.tags.split(",")
and split()
creates an array. You can't parse an array, but you could stringify it
Upvotes: 4