2016-12-26 75 views
0

如果您閱讀我的代碼,您將看到如果請求給出的ID與文檔的Friends數組中的元素相匹配,則用戶不會更新(由於$not運營商)。因此,如果找到並未更新用戶,則返回的結果(myDoc,otherDoc)爲空。我想仍然得到這兩份文件是否已更新。我檢查了貓鼬的文檔,但似乎無法找到解決方案。如果用戶沒有更新(由於條件),findOneAndUpdate返回null

promise.all([ 
User.findOneAndUpdate({id: req.body.myId, Friends: { $not: { $elemMatch: { id: req.body.id }}}}, {$addToSet: { Friends: { id: req.body.id, gender: req.body.gender, emoji: res.locals.myEmoji }}}), 
    User.findOneAndUpdate({id: req.body.id, Friends: {$not: { $elemMatch: {id: req.body.myId }}}}, {$addToSet: { Friends: { id: req.body.myId, gender: req.body.myGender, emoji: res.locals.friendEmoji }}})]) 
.spread(function (myDoc, otherDoc){ 


    ///gives back null if user is not updated 

}).catch(function (err){ 

    return res.status(400).send(err) 

}); 

編輯:有沒有某種貓鼬插件對此有用? ....

+0

你能顯示你的用戶模式嗎? –

+0

是否檢查過您的查詢是否適用於常規查找。如果它在常規查找中返回null而不是更新,那麼您的查詢可能沒有做它應該做的事情。 –

+0

我查了我的朋友。它發現它很好。拉維..這是我的架構VAR userSchema =新模式({ ID:{ 類型:字符串, 獨特:真正的,需要 :真 }, 性別:字符串, 朋友:[屬性] } ); – Ryan

回答

0

如果你想在findOneAndUpdate之後找回更新後的文件,添加一個名爲new的參數並將其設置爲true,就像。

User.findOneAndUpdate({ 
    id: req.body.myId, Friends: { $not: { $elemMatch: { id: req.body.id }}} 
},{ 
    $addToSet:{Friends:{ id: req.body.id, gender: req.body.gender,emoji: res.locals.myEmoji}} 
}, { 
    new: true 
}), 
相關問題