Javascript mongodb查找查询的空白结果
我在MongoShell中运行下面的查询并获得所需的结果Javascript mongodb查找查询的空白结果,javascript,node.js,mongoose,mongodb-query,Javascript,Node.js,Mongoose,Mongodb Query,我在MongoShell中运行下面的查询并获得所需的结果 db.messagelist.find({userID : ObjectId("5e39a9c107357487435d5849")}); 输出 { "_id" : ObjectId("5e39a9c1073574eb1a5d584a"), "message" : "I am at some place", "messageType" : "0", "messageLocation" : "0", "userID" : ObjectId
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之外,所有参数都正常工作。这很奇怪。它甚至不是关键字。尝试使用findOne方法,因为它返回单个对象/任意文档。如果您是通过_id(ducument id)进行查询,请改用findById()
Mongodb中的find方法意味着查找所有文档,因此不需要传递特定属性来查找所需内容。相反,使用findOne并传递属性或findById方法并传递id。尝试
collection.find(id).then(res=>console.log(res)).catch(err=>console.log(err));
问题是userID和id(从参数接收)的表示形式不同
用户ID的格式为:ObjectId(“5e3c13d7b5d89bc92c932243”)
id的格式为:“5e3c13d7b5d89bc92c930000”
这样做,'ObjectId(“+id+”)会导致:ObjectId(\'5e3dc13d7b5d89bc92c930000\”
因此,基本上,userID无法与id或ObjectId(“+id+”)匹配
解决方案:由于其他依赖关系,我无法更改在任何集合中存储id的格式。 因此,我在messagelist集合中创建了一个单独的引用ID(采用所需的格式),以存储来自另一个集合的相应文档的ObjectID
router.get('/messagelist/:id', function (req, res) {
var db = req.db;
var collection = db.get('messagelist');
var id = req.params.id;
collection.findOne({refID: "'"+id+"'"}, {}, function(e, docs) {
docs = JSON.stringify(docs);
res.send(docs);
});
});
尼瑟正在路线上工作。我得到一个空白结果。find查询在mongodb终端中正确获取条件并输出。findOne()也在终端中工作。Niether正在路由中工作。我得到一个空白结果。find查询在mongodb终端中正确获取条件并输出。findOne()也适用于终端。
router.get('/messagelist/:id', function (req, res) {
var db = req.db;
var collection = db.get('messagelist');
var id = req.params.id;
collection.findOne({refID: "'"+id+"'"}, {}, function(e, docs) {
docs = JSON.stringify(docs);
res.send(docs);
});
});