I’m attempting to save an object to my database; I know the database is active, because I’ve read the object in via the same connection being used to update it.
saveAndReturnQuiz = (res, quiz) ->
quiz.save (err) ->
# At some point, started seeing empty object for err, rather than null
if not _.isEmpty err
switch err?.code
when 11000
sendError res, "Quiz title must be unique"
else
console.error "Unexpected error on save(): %j", err
sendError res, extractError err
return
console.log "Sending Quiz response: %j", quiz
res.send quiz
What I’m seeing is that the call to save() is failing, but passing an empty err object.
Here’s my schema:
# Defines the schema of data
# Exports three Mongoose Model objects: Question, Round, and Quiz
mongoose = require "mongoose"
Schema = mongoose.Schema
Question = new Schema
kind:
type: String
enum: [ "text" ]
text:
type: String
required: true
answer:
type: String
required: true
value: Number
{ strict: true }
Round = new Schema
kind:
type: String
required: true
enum: ["normal", "challenge", "wager"]
title:
type: String
required: true
questions: [Question]
{ strict: true }
Quiz = new Schema
title:
type: String
required: true
unique: true
created:
type: Date
default: -> new Date()
location: String
rounds: [Round]
{ strict: true }
module.exports =
Question: mongoose.model('Question', Question)
Round: mongoose.model('Round', Round)
Quiz: mongoose.model('Quiz', Quiz)
So perhaps I’m just dealing with these embedded elements incorrectly?
Interestingly, I can add new Quiz objects to the database, just not update the existing ones:
app.post "/api/quiz",
(req, res) ->
quiz = new Quiz req.body
saveAndReturnQuiz res, quiz
# Update an existing Quiz
app.put "/api/quiz/:id",
(req, res) ->
Quiz.findById req.params.id,
handleError res, (quiz) ->
_.extend quiz, req.body
console.log "Ready to save: %j", quiz
saveAndReturnQuiz res, quiz
A further update: when the model has no nested elements, the update appears to work correctly. It is just when there are nested elements (Rounds, and within Rounds, Questions) that things fail.
I suspect there’s something I’m missing in setting up my schema, but I’m not sure what to check next.
Thanks in advance for any help!
I believe I have solved this; the particular Quiz entity I was saving was one I had modified directly from mongo shell:
I belive the embedded Question entity with no _id proprty was the problem. Creating a new Quiz with Rounds and Questions through my UI, so that every entity has its _id, seems to work fine!