2014-11-24 53 views
0

我有一個運行express的服務器端框架的節點。用mongoose加載並保存mongodb中的文檔

我創建了以下端點:

app.post('/post/save', auth.auth, function (req, res) { 

Post.findById(req.body._id, function (err, post) { 
    post = post || new Post(); 

    post.author.name = req.user.getName(); 
    post.author.id = req.user._id; 
    post.title = req.body.title; 
    post.body = req.body.body; 

    post.save(function (err, object) { 
    err && res.send(500); 
    res.status(200).send({ /*id: object._id*/ }); 
    }); 
}); 

}); 

當我把這個第一次,它的工作原理。 當我第二次打電話時,它失敗。該請求只是保持掛起狀態,並且從save函數調用返回的對象是未定義的。

req.body._idundefined在這兩個請求中。我嘗試連續創建2個新帖子。

我想要做的是檢查一個文檔是否存在,是否存在,更新它然後保存它,或者創建一個新文檔。

我知道像upsert這樣的東西存在,但我不能使用它,因爲我需要預保存中間件來觸發,並且它只在.save之前觸發。

任何人都可以看到錯誤嗎?

+0

你可以做'console.dir(err);'? – Barno 2014-11-24 13:35:11

+0

我有一個E11000重複鍵錯誤索引錯誤,可能是因爲我已經在模型中設置了一個獨特的字段,然後將它評論出來。我認爲如果我刪除了代碼,它就會消失。 – ptf 2014-11-24 14:11:19

+0

可能是您第一次將'post.author.id'創建爲'undefined',並且第二次嘗試使用'undefined'創建另一個帖子時。但是'undefined'已經被使用 – Barno 2014-11-24 14:15:44

回答

0

我原來的職位工作,有一次我從模型中取出unique場,並在數據庫中刪除的集合。

它可能足以放棄索引;見Leonid Beschastnys的評論;

當您將字段設置爲唯一時,Mongoose會在此字段上創建唯一的 索引。即使刪除了 unique:true標誌,該索引仍然存在於MongoDB中。刪除收集索引應該可以解決你的問題 問題

1

如果將邏輯放到回調函數中,然後 - 根據請求查詢值創建或找到Post,傳遞迴調函數?只是不要忘了刪除該任務:post.author.id = req.user._id;

app.post('/post/save', auth.auth, function (req, res) { 
    var callback = function(post) { 
     post.author.name = req.user.getName(); 
     post.title = req.body.title; 
     post.body = req.body.body; 

     post.save(function (err, object) { 
     err && res.send(500); 
     res.status(200).send({ /*id: object._id*/ }); 
     }); 
    }; 

    if (req.body._id) { 
     Post.findById(req.body._id, function (err, post) { 
      callback(post); 
     });   
    } else { 
     var post = new Post(); 
     callback(post); 
    } 
}); 
+0

這可能也適用,但問題是數據庫中的索引。看到我的答案。我會考慮改用這個實現,因爲那樣我會在創建新帖子時爲自己保存一個'findById'調用。 – ptf 2014-11-25 07:52:06

相關問題