Fabriciojf.com Wiki
  • FAQ
    • APIs
      • FAQs Favoritos

        Qual é a sua dúvida?

        •  Página inicial do FAQ
        • Node.js
        • Nodejs: MongoDB find by ObjectId

        Nodejs: MongoDB find by ObjectId

        const res = require('express/lib/response');
        const { MongoClient, ObjectId } = require('mongodb');
        
        function UserDB() {
            MongoClient.connect('mongodb://localhost:7017', function (err, conn) {
                if (err) throw err;
                db = conn.db("mydb");
            });
        }
        
        UserDB.prototype = {
        
            findById: (req, callback) => {
            
                const collection = db.collection('mycollection');
        
                let oid = new ObjectId(req.params.myid);
        
                collection
                    .find({ _id: oid })
                    .toArray(function (err, response) {
                        if (err) throw err;
                        console.log(response);
                        callback(response);
                    });
            };
          
        }
        
        module.exports = new UserDB();
        
         Página inicial do FAQ
        • FAQ
          • APIs
            • FAQs Favoritos

              © Copyright 2026 Fabriciojf.com  Criado por FábioCostaMKT   Pastes   Administração