I need to store responses to questions in Mongo. I am using Mongoose. My query looks like this right now:
router.post('/answers', expressJwt({secret: config.secret}), function (req, res, next) {
var user = req.user
var question = req.body.question
var answer = req.body.answers
var id = question._id
db.User.update({email: user.email}, {$set: {answers[question._id]: answer}}, function (err, doc) {
if (err) {
console.error('problem updating answers object', err)
return res.json(err)
}
console.log(doc)
return res.json('successfully updated answers')
})
})
I get an error 'unexpected token [' How can I add properties to my answers object?
I had to make a db call to get the answers object, then modify it, then update it back to the db. Here is the code I used. Note: use lean and exec with mongoose to get raw object otherwise you will run into problems modifying mongoose objects.
router.post('/answers', expressJwt({secret: config.secret}), function (req, res, next) {
var user = req.user
var question = req.body.question
var answer = req.body.answers
var id = question._id
db.User.findOne({email: user.email}).lean().exec(function (err, user) {
user.answers[question._id] = answer
db.User.update({email: user.email}, {$set: {answers: user.answers}}, function (err, doc) {
if (err) {
console.error('problem updating answers object', err)
return res.json(err)
}
console.log(doc)
return res.json('successfully updated answers')
})
})
})
console.dir(answers[question._id])output?