我正在使用A mongoose查询获取结果并将其作为响应发送

时间:2017-10-16 13:40:01

标签: node.js mongodb

这是我的代码:

    hArr = Array();
    hash.find({ hash_name: new RegExp('^' + req.body.hash + '$', "i") }, function(err, doc) {
        //Do your action here..
        if (err) {

            res.json({ response: 0, data: "fail", message: " Image Downloadding" });
        } else {
            for (var h = 0; h < doc.length; h++)
                hArr.push(doc[h].img_name);
            var unique = hArr.filter(function(elem, index, self) {
                return index == self.indexOf(elem);
            })

            Image.find().where('img').in(unique).exec(function(err, result) {
                res.json({ response: 1, data: result, message: "IMage List" });
            })
        }

    });

当我运行此代码时 它显示

Listening for request
events.js:160
      throw er; // Unhandled 'error' event
      ^
Error: Can't set headers after they are sent.
    at ServerResponse.setHeader (_http_outgoing.js:359:11)
    at ServerResponse.header (E:\learnNode\insta\node_modules\express\lib\response.js:730:10)
    at ServerResponse.send (E:\learnNode\insta\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (E:\learnNode\insta\node_modules\express\lib\response.js:256:15)
    at E:\learnNode\insta\routes\api.js:830:25
    at E:\learnNode\insta\node_modules\mongoose\lib\query.js:2819:18
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

1 个答案:

答案 0 :(得分:0)

确定。根据答案here,您可能会发送多个回复。检查你的代码。当您使用 arr.filter 时,唯一可能包含多个元素。如果是这样,可以多次调用 Image.find 在此路由中发送多个响应。您可以检查它是否将一些console.log的内部循环和回调计数。