0

I am getting this error SyntaxError: Unexpected string in JSON at position 80 at JSON.parse (<anonymous>)

const User = require('../models/user')
const App = require('../models/app')

exports.add_app_to_collection = (req, res) => {
  let application = {}
  App.find({_id: req.body.appId}, (err, app) => {
    application = app

  })

  User.update({
    "_id": req.body.userID, 
    "collections.collName": req.body.collID
  }, 
  {
    $push: {"collections.$.collApps": application
  }})
  .then(result => {
    res.status(200).json({
      message: "the app is added to collection"
    })
  })
}

Both User and App are mongoose models. I expect the problem is inside the first parameter of the update function but I do not know how to solve it. I tried to not to use double quotes for _id and collections.collName but it still does not work.

Note: I used this answer if you want to know what I am doing. Mongodb $push in nested array

x7R5fQ
  • 949
  • 2
  • 13
  • 27
  • 1
    Try printing the JSON first before feeding it to your update function. See if it is a valid JSON. There may be some unwanted characters. You can use any online JSON Pretty tool to check easily. – Tushar Shukla Mar 18 '19 at 03:59
  • Where's the actual JSON? – Jack Bashford Mar 18 '19 at 04:01
  • Q: do I am allowed to use JSON object inside the `update`? I used update function before but only with js objects, not with a JSON object. – x7R5fQ Mar 18 '19 at 04:03
  • All the examples of update function I saw use JS objects not JSON!! – x7R5fQ Mar 18 '19 at 04:05
  • If you add a breakpoint on this update code and go to the point where you see the JSON: Unexpected string error, you'll find the actual problem. I'm not sure for this particular use case but JSON should do good at most of the places where simple JS Object is expected. However JSON should be valid! – Tushar Shukla Mar 18 '19 at 04:08
  • Please mention the code at position 80 at which error is occurred – cEeNiKc Mar 18 '19 at 05:29

0 Answers0