Nice programing

TypeError : db.collection이 함수가 아닙니다.

nicepro 2020. 11. 25. 21:08
반응형

TypeError : db.collection이 함수가 아닙니다.


mLab에서 만든 데이터베이스에 데이터를 게시하려고하는데이 오류가 발생하지만 문제가 무엇인지 모르겠습니다. 또한 이전에이 주제에 대한 질문을 읽었지만 내 오류를 해결할 수 없습니다. 나는 이것에 익숙하지 않다. 그래서 여기에 구현하려는 코드를 게시하고 있으며이 튜토리얼에서 가져 왔습니다. https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes- a07ea9e390d2 .

server.js

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const db = require('./config/db');


const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extened:true}));


MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    require('./app/routes')(app,{});
    app.listen(port,() => {
        console.log("We are live on"+port); 
    });

})

db.js

module.exports = {
  url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing"
};

index.js

const noteroutes = require('./note_routes');

module.exports = function(app,db)
{
    noteroutes(app,db);

};

note_routes.js

module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.collection('notes').insert(note, (err, result) => {
      if (err) { 
        res.send({ 'error': 'An error has occurred' }); 
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};

server.js에서 route / index.js 내보내기 함수가 예상하는대로 데이터베이스를 두 번째 인수로 전달해야하는 빈 객체를 전달합니다.

PFB 업데이트 server.js :

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const db = require('./config/db');

const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extended:true}));

MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    //require('./app/routes')(app,{});
    //check below line changed
     require('./app/routes')(app, database);
    app.listen(port,() => {
        console.log("We are live on"+port); 
    });

});

그래서 나는 그것을 시도했기 때문에 mongodb 2.2.33으로 내려 간다는 대답에 투표했지만 문제를 해결하기 위해 다운 그레이드하는 것이 이상하다고 느꼈기 때문에 버전을 유지할 수있는 해결책을 찾았습니다.> = 3.0. 누군가이 문제를 발견하고 문제가 수락 된 답변과 같은 빈 참조를 전달하지 않은 경우이 솔루션을 시도하십시오.

달릴 때 ..

MongoClient.connect(db.url,(err,database) =>{ }

mongodb 버전> = 3.0에서 해당 database변수는 실제로 액세스하려는 개체의 부모 개체입니다 database.collection('whatever'). 올바른 개체에 액세스하려면 데이터베이스 이름을 참조해야합니다.

MongoClient.connect(db.url,(err,database) =>{ 
  const myAwesomeDB = database.db('myDatabaseNameAsAString')
  myAwesomeDB.collection('theCollectionIwantToAccess')
}

이것은 내 node.js 서버를 실행할 때 내 오류를 수정했으며, 버전을 다운 그레이드하고 싶지 않은 사람에게 도움이되기를 바랍니다.

(또한 어떤 이유로 든 db 이름을 모르는 경우 console.log (database)를 수행하면 개체 속성으로 표시됩니다)


수정 (2018 년 6 월) :

에 따르면 콜백은 실제로 데이터베이스에 연결된 클라이언트 대신 데이터베이스 자체를 반환합니다.

따라서 데이터베이스 인스턴스를 가져 오려면 이 메서드 를 사용해야 합니다 dbName. If not provided, use database name from connection string.아래 주석에서 @divillysausages가 언급했듯이 문서에서라고 말했습니다 .

즉, 우리는 호출해야 database.db().collection('theCollectionIwantToAccess');DBNAME을가이 URL에 의해 제공되는 경우 database실제로 client더 나은 이해를 위해


오류는 mongodb 라이브러리에 있습니다. 버전 설치하려고 2.2.33의를 mongodb. node_modules디렉토리를 삭제 하고 추가

"dependencies": {
   "mongodb": "^2.2.33"
}

그때

npm install

그리고 거기 당신은


MongoClient.connect(uristring, function (err, database) {
      var db=database.db('chatroomApp');
      var collections=db.collection('chats');
});

컬렉션에 액세스하기 전에 먼저 데이터베이스를 가져와야합니다.


mongo 문서에 따르면 다음과 같이 연결을 변경해야합니다.

The legacy operation
MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
    // Database returned
});

is replaced with
MongoClient.connect('mongodb://localhost:27017/test', (err, client) => {
    // Client returned
    var db = client.db('test');
});

mongo 버전을 다운 그레이드 할 필요가 없습니다. :)


기존 mongodb 패키지를 제거하고 다음 명령을 사용하여 다시 설치하면 문제가 해결되었습니다. :)

npm uninstall mongodb --save

npm install mongodb@2.2.33 --save

추신 : @MihirBhende와 @yaxartes 덕분에

참고로,

필드를 처음 사용하는 경우 https://github.com/mongodb/node-mongodb-native/releases의 비 rc 릴리스를 선호 하십시오 .


나는 같은 문제에 부딪쳤다. 동영상이 생성 된 이후 노드 용 mongodb 드라이버 모듈이 업데이트 된 것 같습니다. 작동하는 문서에서 아래 코드를 찾았습니다.

var MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017/<dbName>';
MongoClient.connect(url, (err, db) => {
   db.collection('<collection-name>').find({}).toArray(function(err, docs) {

    // Print the documents returned
    docs.forEach(function(doc) {
        console.log(doc);
    });

    // Close the DB
    db.close();
    });

});  

다음으로 대체됩니다.

 var MongoClient = require('mongodb').MongoClient;

  var url = 'mongodb://localhost:27017'; // remove the db name.
    MongoClient.connect(url, (err, client) => {
       var db = client.db(dbName);
       db.collection('<collection-name>').find({}).toArray(function(err, docs) {

        // Print the documents returned
        docs.forEach(function(doc) {
            console.log(doc);
        });

        // Close the DB
        client.close();
        });

    });  

구문 문제가 더 발생할 경우를 대비하여 최신 문서에 대한 링크 가 있습니다.


module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
  const note = { text: req.body.body, title: req.body.title };
  db.collection('notes').insert(note, (err, result) => {
...

db-> 클라이언트

module.exports = function(app, client) {
  var db = client.db("name");
  app.post('/notes', (req, res) => {
  const note = { text: req.body.body, title: req.body.title };
  db.collection('notes').insert(note, (err, result) => {
...

Dilum Darshana에게 감사드립니다! 귀하의 조언은 많은 도움이되었습니다. 추가하고 싶습니다. promise를 사용하면 다음과 같이 보일 것입니다.

let db;
MongoClient.connect('mongodb://localhost/collectionName').then(connection => {
    db = connection.db('collectionName');
    app.listen(3000, () => {
        console.log("App started on port 3000");
    }); 
}).catch(error => {
    console.log('ERROR:', error);
});

최신 버전의 경우 "mongodb": "^3.1.3"아래 코드를 사용하여 문제를 해결했습니다.

server.js

MongoCLient.connect(db.url,(err,client)=>{
    var db=client.db('notable123');
    if(err){
    return console.log(err);
    }
    require('./server-app/routes')(app,db);
    app.listen(port, ()=> {
        console.log("we are live on : "+ port);
    })

})

그리고 당신의 우편 번호는

module.exports = function(app,db) {
    app.post('/notes',(req,res)=>{
        const note= {text: req.body.body,title:req.body.title};
        db.collection('notes').insertOne(note,(err,result)=>{
            if(err) {
                res.send({"error":"Ann error has occured"}); 
            } else {
                res.send(result.ops[0])
            }
        });
    });
};

package.json에서.

다음 버전이 다음과 같은지 확인하십시오.

"nodemon": "^1.12.1"
"mongodb": "^2.2.33"

위의 nodemon 및 mongodb 버전은 오류없이 함께 작동합니다. 따라서 package.json은 다음과 같아야합니다.

    {
  "name": "myapi",
  "version": "1.0.0",
  "description": "Json Api",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "author": "Riley Manda",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mongodb": "^2.2.33"
  },
  "devDependencies": {
    "nodemon": "^1.12.1"
  }
}

다운 그레이드 후 npm 설치 를 실행하는 것을 잊지 마십시오


이 문제도 있으면 발표자가 컬렉션을 함수로 사용하는 자습서를 따랐습니다. 그것은 나를 위해 일한 적이 없습니다. 내가 발견 한 것은 발표자가 mongodb npm 모듈의 2.3.4 버전을 사용하고 있다는 것입니다. 모듈은 이제 버전 3.xx에 잘 들어 있습니다. mogodb npm 모듈의 2.xx 버전을 요청하기 위해 package.json 파일을 변경했을 때 갑자기 모든 것이 작동했습니다.

내가 믿었던 것은 모듈이 컬렉션을 다른 객체로 변경하도록 변경되었다는 것입니다. 새 버전을 사용하는 방법을 모르지만 2.xx 버전을 원한다고 지정하면 이전 방식이 작동합니다. 특히 내 package.json 파일, "dependencies"섹션에서 오는) "mongodb": "^ 2.2.31"이 작동하는지 확인할 수 있습니다.

가장 좋은 방법은:

$> npm install mongodb@2.2.31 --save

다음을 사용하는 작업 코드 :

npm version 6.0.1,
Node version 10.1.0
"body-parser": "^1.18.3",
"express": "^4.16.3",
"mongodb": "^3.1.0-beta4"
"nodemon": "^1.17.4"

다음은 server.js코드입니다.

const express       = require('express');
const MongoClient   = require('mongodb').MongoClient;
const bodyParser    = require('body-parser');
const db            = require('./config/db');
const app           = express();
const port          = 8000;

app.use(bodyParser.urlencoded({ extended:true }))
MongoClient.connect(db.url, { useNewUrlParser: true },  (err, client)=>{
    var db = client.db('notable');
    if (err) return console.log(err)

    require('./app/routes')(app, client);
    app.listen(port,()=>{
        console.log('we are live at '+ port);
    });
})

다음은 config/db.js코드입니다.

module.exports = {
    url:"mongodb://127.0.0.1:27017"
}

여기 있습니다 routes/note_routes.js:

 var ObjectId = require('mongodb').ObjectID;
 module.exports= function (app, client) {
        var db = client.db('notable');
        //find One
        app.get('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                db.collection('notes').findOne(details, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(item)
                    }
                });
            });
            //update rout
            app.put('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                const note ={text: req.body.body, title: req.body.title};
                db.collection('notes').update(details, note, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(item)
                    }
                });
            });

            //delete route
            app.delete('/notes/:id', (req, res)=>{
                const id =req.params.id;
                const details ={'_id': new ObjectId(id)}
                db.collection('notes').remove(details, (err, item)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send("Note "+id+"deleted!")
                    }
                });
            });
            //insert route
            app.post('/notes', (req, res)=>{
                const note ={text: req.body.body, title: req.body.title};
                db.collection('notes').insert(note, (err, results)=>{
                    if(err)
                    {
                        res.send({'error':"An error has occured"})
                    }
                    else
                    {
                        res.send(results.ops[0])
                    }
                });

            });
        };

연결 URL에 데이터베이스 이름을 사용하지 마십시오.

const mongo_url = 'mongodb://localhost:27017'

대신 아래 방법을 사용하십시오.

MongoClient.connect(mongo_url , { useNewUrlParser: true }, (err, client) => {
        if (err) return console.log(err)
        const  db =  client.db('student')
        const collection = db.collection('test_student');
        console.log(req.body);
        collection.insertOne(req.body,(err,result)=>{
            if(err){
                res.json(err);
            }
            res.json(result);
        });
    });

const MongoClient = require('mongodb').MongoClient;

//connection url

 const url = 'mongodb://localhost:27017/myproject';

 MongoClient.connect(url,{useNewUrlParser: true},(err,client)=> {
  if(err) {
    return console.dir(err)
  }

   console.log('Connected to MongoDB')

  //get the collection
  let db = client.db('myproject');
  db.collection('users').insertOne({
  name: 'Hello World',
  email: 'helloworld@test.com'

  },(err,result)=> {
  if(err) {
      return console.dir(err)
  }
  console.log("Inserted Document");
  console.log(result);

     });
   });

나는 간단한 해결책이 있습니다.

note_routes.js

db.collection('notes').insert(note, (err, result) => {

바꾸다

db.db().collection('notes').insert(note, (err, result) => {

참고 URL : https://stackoverflow.com/questions/43779323/typeerror-db-collection-is-not-a-function

반응형