0

我正在尝试将对象保存到我的数据库中;我知道数据库处于活动状态,因为我已经通过用于更新它的同一连接读取了对象。

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

我看到的是对 save() 的调用失败,但传递了一个空的 err 对象。

这是我的架构:

# 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)

所以也许我只是错误地处理了这些嵌入元素?

有趣的是,我可以将新的 Quiz 对象添加到数据库中,而不是更新现有的对象:

  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

进一步更新:当模型没有嵌套元素时,更新似乎可以正常工作。只是当有嵌套元素(回合,回合内,问题)时,事情才会失败。

我怀疑在设置架构时缺少一些东西,但我不确定接下来要检查什么。

提前感谢您的帮助!

4

1 回答 1

0

我相信我已经解决了这个问题;我保存的特定测验实体是我直接从 mongo shell 修改的:

> db.quizzes.find( {title: "NFJS" }).pretty()
{
  "_id" : ObjectId("4f835669c34c2a9c6f000003"),
  "created" : ISODate("2012-04-09T21:36:41.726Z"),
  "location" : "San Antonio",
  "rounds" : [
    {
      "_id" : ObjectId("4f835669c34c2a9c6f000004"),
      "kind" : "normal",
      "questions" : [
        {
          "kind" : "text",
          "answer" : "My Answer",
          "value" : 10,
          "text" : "My Question"
        }
      ],
      "title" : "Server-Side Java and JavaScript"
    },
    {
      "kind" : "normal",
      "title" : "Underscore / Bootstrap Trivia",
      "_id" : ObjectId("4fa317319b19aca4c900004c"),
      "questions" : [ ]
    }
  ],
  "title" : "NFJS"
}

我相信没有 _id 属性的嵌入式 Question 实体是问题所在。通过我的 UI 创建一个包含回合和问题的新测验,以便每个实体都有其 _id,似乎工作正常!

于 2012-05-10T17:52:11.947 回答