2015-10-14 196 views
0

如何在Mongoose中編寫一個我想在數組中搜索的查詢,如果值不存在,那麼我想更新我的文檔。我已經閱讀了許多StackOverflow答案,但沒有指定如何在數組操作中使用它。我的查詢也在下面給出。有人可以告訴我如何做到這一點,我一直在這裏卡住了。 在下面的代碼,我想在裏面找reg_ids數組,如果沒有它的價值包含reg_id這是一個字符串,那麼我想更新我的文檔Mongoose查詢返回不包含特定字段的數組?

userregidsmodel.findOneAndUpdate(
    {email_id: jeeb_no, reg_ids: { $ne: reg_id } }, 
    {$push: {reg_ids: reg_id} }, 
    {'total_follow_notifications': 1, 'total_notifications': 1, '_id':0}, 
    function(err, docs) { 
    if (err) { 
     console.log('Error Finding query results'); 

     console.log(err); 
     res.json({success: 0, message : err}); 
     return next(err); 
    } else { 
     if (docs) { 
     console.log('Login Successfull'); 
     res.json({success : 1, message : "Login Successfull", mobile_no: mobile_no, email_id: email_id}); 
     return next(); 
     } else { 
     console.log('login Successfull app previous token is used'); 
     res.json({success : 1, message : "Login Successfull", mobile_no: mobile_no, email_id: email_id}); 
     return next(); 
     } 
    } 
    }); 
+2

什麼是不工作呢? ['findOneAndUpdate'](http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate)的第三個參數是一個選項參數,不只是字段選擇參數,而是代碼看起來正確。 – JohnnyHK

+0

以及如何在finOneAndUpdate中選擇字段? –

+1

將它傳遞爲'{select:{'total_follow_notifications':1,'total_notifications':1,'_id':0}}'。 – JohnnyHK

回答

1

findOneAndUpdate第三個參數是一個選項參數,不只是一個字段選擇參數,所以你需要用你的領域選擇的對象在{select: ...}對象:

userregidsmodel.findOneAndUpdate(
    {email_id: jeeb_no, reg_ids: { $ne: reg_id } }, 
    {$push: {reg_ids: reg_id} }, 
    {select: {'total_follow_notifications': 1, 'total_notifications': 1, '_id':0}}, 
    function(err, docs) { ... 
相關問題