【问题标题】:Checking documents from MongoDb with if(==) operator in NodeJs在 NodeJs 中使用 if(==) 运算符检查来自 MongoDb 的文档
【发布时间】:2020-08-01 10:00:43
【问题描述】:

我有问题如何使用 if 运算符在 NodeJs 中检查 MongoDb 中的特定文档。

我的 MongoDb 集合看起来像这样(我只需要文档“按钮”):

{
    "_id" : ObjectId("5e95eb9da19c2430d4952754"),
    "title" : "Krepšinis",
    "author" : "5e90eb1abbcb1f33e8b17720",
    "place" : "dsadas",
    "count" : 10,
    "going_count" : 5,
    "button" : "Būsiu",
    "__v" : 0
}

我的 NodeJ:

router.post('/:id', function(req, res){
  let post = {};
  if(post.button == "Būsiu"){
     post.button = "Nebūsiu";
  } else {
     post.button = "Būsiu";
  }


 let query = {_id:req.params.id}

 Post.update(query, post, function(err){
   if(err){
     console.log(err);
     return;
   }
   req.flash('success', 'Postas Atnaujintas');
   res.send('Success');
  });
});

问题是我没有收到任何错误,它只是不起作用。

这是我的 Ajax:

$(document).ready(function(){
  $('.going').on('click', function(e){
    console.log('working')
    $target = $(e.target);
    const id = ($target.attr('data-id'));
    $.ajax({
      type:'POST',
      url: '/posts/'+id,
      success: function(response){
      alert('Važiuojam');
      },
      error: function(err){
      console.log(err);
     }
    });
   });
  });

我真的不知道还能尝试什么,因为我对编程很陌生。

【问题讨论】:

    标签: node.js mongodb web-applications


    【解决方案1】:

    你可以尝试指定mongodb聚合管道,并检查查询中受影响文档的结果如下

        router.post('/:id', function(req, res){
        let post= {};
        if(post.button == "Būsiu"){
        post.button = "Nebūsiu";
        } else {
         post.button = "Būsiu";
        }
        let query = {_id:req.params.id}
        Post.update(query, {$set:post}, function(err, response
        ){ 
       if(err){
         console.log(err);
         return;
        }
       console.log(response.result.nModified)
       req.flash('success', 'Postas Atnaujintas');
       res.send('Success');
        });
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-25
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多