在node.js应用中基于Mongo ID查询MongoDB [英] Querying a MongoDB based on Mongo ID in a node.js app

查看:65
本文介绍了在node.js应用中基于Mongo ID查询MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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完全匹配,但是从数据库查询中得到的响应为空.

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,并匹配db中的_id!

This converts my string into a mongo ObjectId and matches the _id in the db!

这篇关于在node.js应用中基于Mongo ID查询MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆