MongoError $ regex必须是一个字符串

时间:2016-10-03 02:03:10

标签: javascript html ajax node.js mongodb

问题是,我在控制台上收到错误

{ [MongoError: $regex has to be a string]
  name: 'MongoError',
  message: '$regex has to be a string',
  waitedMS: 0,
  ok: 0,
  errmsg: '$regex has to be a string',
  code: 2 }

基本上我正在做的是,我使用ajax从我的MongoDB获取数据,我在那里搜索用户。没有ajax,我的搜索功能正常工作。但我想搜索一个用户,而不需要刷新网页,只是填写我的HTML。这是我的代码

服务器代码:

app.post("/searchresult", function(req, res){
    var thename = req.body.thename;
    LoginUser.find({
        $or: [

            {"firstname": {$regex: thename, $options: 'i'}},
            {"lastname": {$regex: thename, $options: 'i'}}
        ]
    }, function(err, searchedUser){
        if(err){
            console.log(err);
            res.redirect("back");
        } else {
            res.render("searchprofile", {foundUser: searchedUser});
        }
    });
});

HTML code:

<form class="form-inline" id="searchform" action="/searchresult" method="POST">
   <input type="text" class="form-control" placeholder="Search people" name="thename" id="searchinput">
   <button type="submit" class="btn btn-default">Submit</button>
</form>

jQuery代码:

$("#searchform").on('submit', function(e){
  e.preventDefault();

  var searchInp = $("#searchinput");

  $.ajax({
    url: '/searchresult',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ firstname: searchInp.val() }),
    success: function(response){
      console.log(response);
      searchInp.val('');
    }
  });
});

2 个答案:

答案 0 :(得分:1)

// thename = ${thename}

登录用户.find({ $或:[

    {"firstname": {$regex: `${thename}`, $options: 'i'}},
    {"lastname": {$regex: `${thename}`, $options: 'i'}}
]

},

答案 1 :(得分:0)

检查您的数据可能 不是字符串。