我在mongo shell中运行以下查询,并获得所需的结果。
db.messagelist.find({userID : ObjectId("5e39a9c107357487435d5849")});
输出
{ "_id" : ObjectId("5e39a9c1073574eb1a5d584a"), "message" : "I am at some place", "messageType" : "0", "messageLocation" : "0", "userID" : ObjectId("5e39a9c107357487435d5849"), "timeStamp" : "'1580837313163'" }
但是当我按如下方式为其创建路由时,它返回空白结果:
router.get('/messagelist/:id', function (req, res) {
var db = req.db;
var collection = db.get('messagelist');
var id = req.params.id;
//console.log("id is: "+id);
//collection.find({userID : 'ObjectId("'+id+'")'});
collection.find({"userID" : id}, {}, function (e, docs) {
docs = JSON.stringify(docs);
console.log("docs: "+docs); //empty
res.send(docs);
});
});
语法是否有问题?!有任何建议。
编辑:
此查询也有效。因此,在这种情况下,语法是正确的。我不知道userID有什么问题。
router.get('/messagelist/:id', function (req, res) {
var db = req.db;
var collection = db.get('messagelist');
var id = req.params.id;
//console.log("id is: "+id);
//db.messagelist.find({userID : 'ObjectId("'+id+'")'});
collection.findOne({_id : id}, function(e, docs) {
console.log("docs: "+docs);
docs = JSON.stringify(docs);
console.log("docs: "+docs);
res.send(docs);
});
});
除userID的情况外,所有参数均有效。真奇怪。它甚至不是关键字。
答案 0 :(得分:0)
尝试使用findOne方法,因为它返回单个对象/任意文档。如果要通过_id(提示ID)进行查询,请改用findById()。
答案 1 :(得分:0)
查找方法意味着查找所有文档,因此您无需传递特定的属性即可查找所需的内容。而是使用 findOne 并传递属性或 findById 方法并传递ID。
答案 2 :(得分:0)
尝试
collection.find(id).then(res=>console.log(res)).catch(err=>console.log(err));
答案 3 :(得分:0)
StringBuilder driverIds = new StringBuilder();
for (Driver driver : driverList) {
driverIds.append(driver.getDriverId()).append(STRING_SEPARATOR_COMMA);
}
HttpEntity<String> entity = new HttpEntity(requestHeader);
UriComponentsBuilder uriBuilder = constructUriForGetDriverOrContractList (endpointContractService,PATH_SEGMENT_CONTRACT,serviceRequestContext, clientId, driverIds.toString()); return Arrays.asList(Objects.requireNonNull(restTemplate.exchange(uriBuilder.toUriString(), HttpMethod.GET,entity, Contract[].class).getBody()));
问题是userID和id(从参数接收)的表示形式不相同。
用户ID 的格式为: router.get('/messagelist/:id', function (req, res) {
var db = req.db;
var collection = db.get('messagelist');
var id = req.params.id;
//collection.find({userID : 'ObjectId("'+id+'")'});
collection.find({"userID" : id}, {}, function (e, docs) {
docs = JSON.stringify(docs);
res.send(docs);
});
});
id 的格式为: ObjectId("5e3c13d7b5d89bc92c932243")
执行此操作,'ObjectId(“'+ id +'”)'会导致以下结果: "5e3c13d7b5d89bc92c930000"
因此,基本上 userID 与 id 或'ObjectId(“'+ id +'”)'
不匹配 解决方案:
由于其他依赖关系,我无法更改ID在任何集合中存储的格式。
因此,我在messagelist-collection中创建了一个单独的referenceID(以所需的格式),用于存储另一个集合中相应文档的objectIds。
"ObjectId(\"5e3c13d7b5d89bc92c930000\")"