在 node.js 应用程序中根据 Mongo ID 查询 MongoDB [英] Querying a MongoDB based on Mongo ID in a node.js app
问题描述
我正在使用 node.js 和 mongodb,并且我正在尝试使用以下命令根据 mongo 生成的 ID 查询数据库:
I'm using a node.js and mongodb, and I'm trying to query the database based on the mongo generated ID using the following:
collection.findOne( {_id:doc._id} , function(err, item) {});
我 100% 确定我的 doc._id 与我在集合中查找的 doc _id 完全匹配,但我从 db 查询中得到了空响应.
I am 100% certain that my doc._id is an exact match to the doc _id that I am looking for in the collection, and yet I get a null response from the db query.
我已经使用文档中的其他键尝试过这个,它返回文档就好了.只有当我尝试使用 mongo ID 时.
I have tried this using other keys in the document and it returns the document just fine. It's only when I try to use the mongo ID.
推荐答案
MongoDb 是一个对象而不是字符串.转换我使用的字符串:
The MongoDb is an object not a string. To convert my string I used:
var id = require('mongodb').ObjectID(doc._id);
这会将我的字符串转换为 mongo ObjectId 并匹配数据库中的 _id!
This converts my string into a mongo ObjectId and matches the _id in the db!
这篇关于在 node.js 应用程序中根据 Mongo ID 查询 MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!