mongoose 查询时将返回结果排除_id,报错,求解答
发布于 6 年前 作者 ersSan 2336 次浏览 来自 问答

代码如下,我也用了这个帖子中所说的方法 如何在mongoose中执行find命令不返回_id字段?**,一样报错,没找出来什么原因。但如果不排除 _id 就不会报错

代码如下

function userLogin(option, callback) {
    userModel.findOne(option, {"_id":0}).exec(function (err, result){
        if (err) console.log(err);
        callback(result);
    })
}

报错如下

(node:19840) UnhandledPromiseRejectionWarning: MongooseError: No _id found on document!
    at new MongooseError (G:\train\project\Collector\node_modules\_mongoose@5.2.13@mongoose\lib\error\mongooseError.js:13:11)
    at model._where [as $__where] (G:\train\project\Collector\node_modules\_mongoose@5.2.13@mongoose\lib\model.js:778:12)
    at model.Model.$__handleSave (G:\train\project\Collector\node_modules\_mongoose@5.2.13@mongoose\lib\model.js:217:26)
    at model.Model.$__save (G:\train\project\Collector\node_modules\_mongoose@5.2.13@mongoose\lib\model.js:255:8)
    at G:\train\project\Collector\node_modules\_kareem@2.2.1@kareem\index.js:278:20
    at _next (G:\train\project\Collector\node_modules\_kareem@2.2.1@kareem\index.js:102:16)
    at process.nextTick (G:\train\project\Collector\node_modules\_kareem@2.2.1@kareem\index.js:452:38)
    at process._tickCallback (internal/process/next_tick.js:61:11)
(node:19840) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:19840) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
3 回复

首先确定正常情况下有没有数据,其次既然用回调方式就不要用exec函数了。再说错误提示说的是在文档中没有找到_id

没遇到过。。。mongoose最新的代码里目前只看到model的内部方法在文档没有_id字段的时候会报这个错误,但实际上mongodb本身是支持这样的projection操作的,mongoose很多都只是对mongodb的API的实现,按理说应该保持一致。怀疑是mongoose的bug。

之前mongoose在调用save方法有过这种issue,你可以看一下你在用的mongoose版本是否有这个问题。

最好的办法是去mongoose的github上提交issue。

回到顶部