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

后端 未结 5 1167
夕颜
夕颜 2020-12-10 02:57

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         


        
5条回答
  •  伪装坚强ぢ
    2020-12-10 03:29

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

    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:

    //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.

提交回复
热议问题