Javascript 在 node.js 应用程序中根据 Mongo ID 查询 MongoDB

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12769252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:12:52  来源:igfitidea点击:

Querying a MongoDB based on Mongo ID in a node.js app

javascriptnode.jsmongodbexpressmongodb-query

提问by user699242

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:

我正在使用 node.js 和 mongodb,并且我正在尝试使用以下命令根据 mongo 生成的 ID 查询数据库:

    collection.findOne( {_id:doc._id} , function(err, item) {});

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.

我 100% 确定我的 doc._id 与我在集合中查找的 doc _id 完全匹配,但我从 db 查询中得到了空响应。

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.

我已经使用文档中的其他键尝试过这个,它返回文档就好了。只有当我尝试使用 mongo ID 时。

回答by user699242

The MongoDb is an object not a string. To convert my string I used:

MongoDb 是一个对象而不是一个字符串。要转换我使用的字符串:

    var id = require('mongodb').ObjectID(doc._id);

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

这会将我的字符串转换为 mongo ObjectId 并匹配数据库中的 _id!

回答by Krishan Kumar

Use this:

用这个:

ObjectId = require('mongodb').ObjectID;

Then when you try to find an object in collection by _id use this:

然后,当您尝试通过 _id 在集合中查找对象时,请使用以下命令:

 console.log("find by: "+ id);
 database.collection("userRegister").findOne({_id: new ObjectId(id)}, 
   function(err, res) { 

     if (err) console.log(err);

     if(res!=null){
       console.log(res)
       return false;
     }

     if(res==null){
       callback({'status':_error,'flag':'notexist','message':_userNotExist});
       return false;
     }

   });

回答by Amol M Kulkarni

Following is the example which spots the issue:

以下是发现问题的示例:

var mongo = require('mongodb'),
    Server = mongo.Server,
    Db = mongo.Db,
    ObjectID = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient

//let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'...
var obj_id = new ObjectID('52cbd028e9f43a090ca0c1af');
var justId = '52cbd028e9f43a090ca0c1af'; // <== This will not work

MongoClient.connect('mongodb://127.0.0.1:27017/YourDbName', function(err, db) {
    console.log('err'  +  err);
    db.collection('YourCollectionName', function(error, collection) {
        //collection.find({_id:justId}),function(err, docs) { // <== This will not work
        collection.findOne({_id:obj_id},function(err, docs) {
          console.log("Printing docs from Array. count " + JSON.stringify(docs)); 
        });
  });
});

回答by KARTHIKEYAN.A

First we need to get ObjectIDfrom mongodblibrary and need to create new instance in following way., so that you will get the ObjectID of string. If your are using es6in your code this code

首先我们需要ObjectIDmongodb库中获取,并需要通过以下方式创建新实例,以便您将获得字符串的ObjectID。如果您在代码中使用es6,请使用此代码

import { ObjectID } from 'mongodb';

var emQuery = [
          {
            $match: {
              _id: new ObjectID(tlvaltResult[0].customers.createdBy)
            }
          },
          {
            $project: {
              _id:1,
              emailId:1,
              mobile:1
            }
          }
        ];

console.log(emQuery,'emQuery');

[ { '$match': { _id: 5ad83ff0b443435298741d3b } },
  { '$project': { _id: 1, emailId: 1, mobile: 1 } } ] 

var emResult = await User.getAggregation(emQuery);

console.log(emResult,'emResult');

[ { _id: 5ad83ff0b443435298741d3b,
    emailId: '[email protected]' } ]

回答by f1nn

First, ensure you've added all required modules in MongoDB config:

首先,确保您已在 MongoDB 配置中添加了所有必需的模块:

var mongo = require('mongodb'),
    Server = mongo.Server,
    Db = mongo.Db,
    ObjectID = require('mongodb').ObjectID;
var BSON = require('mongodb').BSONPure;
var server = new Server('localhost', 27017, {
    auto_reconnect: true
});
var db = new Db('YOUR_DB_NAME', server);

Then, when you try to find an object in collection by _id, use:

然后,当您尝试通过 _id 在集合中查找对象时,请使用:

//let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'...
var obj_id = BSON.ObjectID.createFromHexString(id);
db.collection("NAME_OF_COLLECTION_WHERE_IS_YOUR_OBJECT", function(error, collection) {
    collection.findOne( {_id:obj_id} , function(err, item) {
        // console.log ( item.username );
    });
});

Hope, this works.

希望,这有效。