2012-05-09 58 views
0

我試圖將一個對象保存到我的數據庫;我知道數據庫是活動的,因爲我已經通過用於更新它的相同連接讀取對象。調用Mongoose document.save()似乎不能保存?

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) 

因此,也許我只是處理錯誤,這些嵌入元素?

有趣的是,我可以添加新的測驗對象數據庫,只是沒有更新現有的:

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 

進一步更新:當該模型沒有嵌套元素,更新似乎正常工作。正是在嵌套元素(Rounds,以及Rounds,Questions)中,事情失敗了。

我懷疑在設置我的模式時缺少某些東西,但我不確定接下來要檢查什麼。

在此先感謝您的幫助!

回答

0

我相信我已經解決了這個問題;我節省了特定測驗的實體是一個我直接從蒙戈外殼修改:

> 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 proprty是問題。通過我的用戶界面創建一個新的測驗,通過回合和問題,以便每個實體都有它的_id,似乎工作正常!