node.js mongodb select document by _id node-mongodb-native

后端 未结 10 1489
死守一世寂寞
死守一世寂寞 2020-12-02 08:28

I\'m trying to select a document by id

I\'ve tried:

collection.update({ \"_id\": { \"$oid\": + theidID } }

collection.update({ \"_id\": theidID }

c         


        
相关标签:
10条回答
  • 2020-12-02 08:43

    If you use Mongosee, you can simplify the function

    FindById:

    this replace in mongodb: "_id" : ObjectId("xyadsdd434434343"),

    example:
    
    // find adventure by id and execute
    Adventure.findById('xyadsdd434434343', function (err, adventure) {});
    

    https://mongoosejs.com/docs/api.html#model_Model.findById

    0 讨论(0)
  • 2020-12-02 08:44

    The answer depends upon the variable type you are passing in as the id. I pulled an object id by doing a query and storing my account_id as the ._id attribute. Using this method you simply query using the mongo id.

    // begin account-manager.js
    var MongoDB   = require('mongodb').Db;
    var dbPort      = 27017;
    var dbHost      = '127.0.0.1';
    var dbName      = 'sample_db';
    db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
    var accounts = db.collection('accounts');
    
    exports.getAccountById = function(id, callback)
    { 
      accounts.findOne({_id: id},
        function(e, res) {  
        if (e) {
            callback(e)
        }
        else {
            callback(null, res)
        }
    
      });
    }
    // end account-manager.js
    
    // my test file
    var AM = require('../app/server/modules/account-manager');
    
    it("should find an account by id", function(done) {
    
    AM.getAllRecords(function(error, allRecords){
      console.log(error,'error')
      if(error === null) {
        console.log(allRecords[0]._id)
        // console.log('error is null',"record one id", allRecords[0]._id)
        AM.getAccountById(          
          allRecords[0]._id,
          function(e,response){
            console.log(response,"response")
            if(response) {
              console.log("testing " + allRecords[0].name + " is equal to " + response.name)
              expect(response.name).toEqual(allRecords[0].name);
              done();    
            } 
          }
        )  
      } 
    })
    

    });

    0 讨论(0)
  • 2020-12-02 08:51
    var mongo = require('mongodb');
    var o_id = new mongo.ObjectID(theidID);
    collection.update({'_id': o_id});
    
    0 讨论(0)
  • 2020-12-02 08:51

    I'm using client "mongodb": "^3.6.2" and server version 4.4.1

    // where 1 is your document id
    const document = await db.collection(collection).findOne({ _id: '1' })
    console.log(document)
    

    If you want to copy and paste here's all you need.

    const { MongoClient } = require('mongodb')
    const uri = '...'
    const mongoDb = '...'
    const options = {}
    ;(async () => {
      const client = new MongoClient(uri, options)
      await client.connect()
      const db = client.db(mongoDb)
      const document = await db.collection(collection).findOne({ _id: '1' })
      console.log(document)
    )}()
    
    0 讨论(0)
  • 2020-12-02 08:52

    This the approach that worked for me.

    var ObjectId = require('mongodb').ObjectID;
    
    var get_by_id = function(id, callback) {
      console.log("find by: "+ id);
      get_collection(function(collection) {
        collection.findOne({"_id": new ObjectId(id)}, function(err, doc) {
           callback(doc);
        });
      });
    }
    
    0 讨论(0)
  • 2020-12-02 08:53

    With native_parser:false:

    var BSON = require('mongodb').BSONPure;
    var o_id = BSON.ObjectID.createFromHexString(theidID);
    

    With native_parser:true:

    var BSON = require('mongodb').BSONNative;
    var o_id = BSON.ObjectID.createFromHexString(theidID);
    
    0 讨论(0)
提交回复
热议问题