2015-10-14 78 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) { ... 
相关问题