【发布时间】:2019-07-09 22:57:15
【问题描述】:
我是 MongoDB/Mongoose 的新手,最近开始了一个使用 MongoDB、Node 和 Express 的项目,我遇到了一个问题,当尝试在存在的 _id 上使用 mongoose 进行查询时,结果为空。我发现了类似的问题,但大多数情况下 mongoose 正在查询复数集合名称,我通过打开 mongoose 的调试并验证集合是否正确命名来确认这不是我的问题。
我的文档位于报告数据库和客户集合中,该集合中目前只有一个文档。
{
"_id" : ObjectId("5c64881002ea07789e9444aa"),
"fields" : {
"Customer ID" : "_id",
"First Name" : "first_name",
"Last Name" : "last_name",
"Contact Type" : "opt_history.contact_type",
"Opt In Date" : "opt_history.opt_in_date",
"Opt Out Date" : "opt_history.opt_out_date",
"Location Opt In" : "opt_history.location_opt_in",
"Location Opt Out" : "opt_history.location_opt_out"
},
"filters" : {
"company" : {
"validation" : {
"required" : true
},
"query_value" : "company:%company_id%"
},
"opt_history" : {
"validation" : {
"required" : true
},
"query_value" : {
"opt_in" : {
"if" : {
"start_date" : {
"if" : {
"end_date" : "{$and: [{\"opt_history.opt_in_date\":{$gte: %start_date%, $lte: %end_date%}}, {\"opt_history.opt_out_date\":{$eq: null}}]}"
},
"else" : "{$and: [{\"opt_history.opt_in_date\":{$eq: %start_date%}}, {\"opt_history.opt_out_date\":{$eq: null}}]}"
}
},
"else" : "{$and: [{\"opt_history.opt_in_date\":{$ne: null}}, {\"opt_history.opt_out_date\":{$eq: null}}]}"
},
"opt_out" : {
"if" : {
"start_date" : {
"if" : {
"end_date" : "opt_history.opt_out_date:{$gte: %start_date%, $lte: %end_date%}"
},
"else" : "opt_history.opt_out_date:{$eq: %start_date%}"
}
},
"else" : "opt_history.opt_out_date:{$ne: null}"
},
"no_opt" : "{$or: [{\"opt_history\":null}, {\"opt_history.opt_out_date\":{$nin:[null]}}]}"
}
}
}
}
用于获取文档的代码如下(FWIW我尝试了字符串_id和ObjectId,结果相同):
exports.run = function(req, res, next) {
console.log(req.query.id);
const report = require('../models/Report');
report.findById("5c64881002ea07789e9444aa").exec(function(err, result) {
console.log(err);
console.log(result);
res.send(result);
});
};
我已经打开了 mongoose 的调试,可以看到正在形成的查询是 customer.findOne({ _id: ObjectId("5c64881002ea07789e9444aa") }, { projection: {} }),我试图直接在 mongodb 中运行该查询并得到以下错误。
db.customer.findOne({ _id: ObjectId("5c64881002ea07789e9444aa") }, { projection: {} })
2019-02-15T11:27:51.425-0700 E QUERY [js] Error: error: {
"ok" : 0,
"errmsg" : ">1 field in obj: {}",
"code" : 2,
"codeName" : "BadValue"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBCommandCursor@src/mongo/shell/query.js:708:1
DBQuery.prototype._exec@src/mongo/shell/query.js:113:28
DBQuery.prototype.hasNext@src/mongo/shell/query.js:288:5
DBCollection.prototype.findOne@src/mongo/shell/collection.js:260:10
@(shell):1:1
似乎问题出在猫鼬似乎注入我的查询中的“投影:{}”。当我删除该部分时,查询将在 mongodb 中运行良好。所以问题是,为什么猫鼬会这样做,我能做些什么来抑制它?我想要整个文档,所以我不需要投影任何字段。
【问题讨论】:
-
控制台中的错误是您需要在投影中至少有 1 个字段。
-
好的,我试过了,但收到一条错误消息,指出“不支持的投影选项:投影 {filters:1.0}”。如果我从查询中删除“投影;{过滤器:1.0}”部分,它运行得很好。所以看来我实际上并不需要一个投影,这引出了一个问题,为什么猫鼬会在我不告诉它的时候添加一个?
标签: javascript node.js mongodb mongoose mean