MongoClient v3.0을 사용할 때 db.collection이 함수가 아닙니다


132

MongoDB를 사용하여 nodeJS에서 W3schools 자습서 를 시도 했습니다 .

nodeJS 환경 에서이 예제를 구현하고 AJAX 호출로 함수를 호출하려고하면 아래 오류가 발생합니다.

TypeError: db.collection is not a function
    at c:\Users\user\Desktop\Web Project\WebService.JS:79:14
    at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5
    at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

구현 된 코드를 아래에서 찾으십시오.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestingdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  db.collection("customers").findOne({}, function(err, result) {
    if (err) throw err;
    console.log(result.name);
    db.close();
  });
});

실행이 발생할 때마다 오류가 발생합니다.

db.collection("customers").findOne({}, function(err, result) {}

또한 노드 JS 용 최신 MongoDB 패키지 ( npm install mongodb )를 설치 했으며 MongoDB 버전은 MongoDB Enterprise 3.4.4이며 MongoDB Node.js 드라이버 v3.0.0-rc0입니다.


(1) 데이터베이스가 실행 중입니다 (오류가없는 경우). (2) mytestingdb 데이터베이스가 존재합니다 (robomongo / robo3t를 사용하여 연결에 액세스하고 콜렉션을보십시오) (3) 콜렉션 고객이 실제로 존재합니다. 또한 어떻게 스크립트를 호출하고 어떤 버전의 Nodejs를 어떻게 설치했는지 알려주십시오 (어떻게 설치 했습니까?)
nbkhope

데이터베이스와 컬렉션이 존재합니다 (Studio 3t를 사용하여 액세스했습니다). AJAX 호출을 통해 메소드를 호출하여 nodeJS를 디버깅하고 있습니다. 기본적으로 중단 점이 발생하고 위에서 언급 한 예외를 얻을 때까지 모든 것이 올바르게 작동합니다. NodeJS 버전은 v6.11.4입니다.
Elie Asmar

그런 다음 db.collection()...콘솔 로그로 시작하는 코드를 교체하여 문제가 없는지 확인하십시오.
nbkhope

데이터베이스와 컬렉션이 존재합니다 (Studio 3t를 사용하여 액세스했습니다). AJAX 호출을 통해 메소드를 호출하여 nodeJS를 디버깅하고 있습니다. 기본적으로 중단 점이 발생하고 위에서 언급 한 예외를 얻을 때까지 모든 것이 올바르게 작동합니다. NodeJS 버전은 v6.11.4입니다.
Elie Asmar

답변:


80

나는 같은 것을 만났다. package.json에서 mongodb 행을 "mongodb": "^ 2.2.33"으로 변경하십시오. mongodb를 npm 제거해야합니다. 그런 다음 npm install로이 버전을 설치하십시오.

이것은 나를 위해 문제를 해결했습니다. 버그 인 것 같거나 문서를 업데이트해야합니다.


15
check MikaS 'answer
hartmut

67
이전 버전으로 다운 그레이드하는 것은 실제로 해결책이 아닙니다. 이로 인해 API 변경을 고려하지 않았 음을 의미합니다.
John Culviner

3
@JohnCulviner-타이밍 문제였습니다. 게으름 문제가 아닙니다. 이 문제는 새 업데이트를 배포하는 중 발생했습니다. 나는 (그리고 원래 포스터) 분명히 이것을 깨닫지 못했습니다. 당시 문서는 아직 업데이트되지 않았습니다. 그들은 곧 업데이트되었습니다. 현재이 문제를 해결하려는 사람은 MikaS의 의견을 따라 업데이트 된 문서를 검토해야합니다. 문서가 업데이트 된 후에도 동일한 작업을 수행하고 업그레이드 된 버전을 계속 사용할 수있었습니다.
AyoO

1
지금이 문제가 발생했습니다.이 문제가 발생하여 package.json에 "mongodb :" "3.0.2"가 설치되어 있습니다. 새 버전에 문제가 있습니까?
logos_164

4
전혀 도움이되지 않습니다. 정답으로 표시되는 이유는 무엇입니까?
CodingNow

482

MongoDB 원시 NodeJS 드라이버 버전 3.0 사용자 :

( "mongodb": "^ 3.0.0-rc0"또는 package.json의 최신 버전 인 최신 버전을 계속 사용하려는 사용자에게 적용됩니다.)

MongoDB 원시 NodeJS 드라이버 버전 2.x에서는 데이터베이스 오브젝트를 연결 콜백에 대한 인수로 가져옵니다.

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

3.0 에 대한 changelog 에 따르면 이제 데이터베이스 오브젝트를 포함하는 클라이언트 오브젝트를 얻게됩니다.

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

close()방법은 또한 클라이언트로 이동되었습니다. 따라서 문제의 코드는 다음과 같이 번역 될 수 있습니다.

MongoClient.connect('mongodb://localhost', function (err, client) {
  if (err) throw err;

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
}); 

이제 우리는 이런 식 ( var db = client.db('mytestingdb');)을 쓰는 대신 매번 이 ( ) 여분의 행을 작성 MongoClient.connect('mongodb://localhost:27017/mytestingdb')해야합니까? 나는 항상 같은 데이터베이스로 작업하고 있습니다. 그 여분의 선을 제거하는 접근법이 있습니까? 그것은 시간이 걸리는 것과 같습니다.
ozgrozer

7
@ozgrozer 모든 요청에 ​​대해 DB에 연결하는 것처럼 들립니다. 그것은 나쁜 생각으로 간주됩니다. 여기에서 읽을 수 있습니다 . 한 번만 연결하면 만드는 앱마다 하나의 줄만 생깁니다.
Mika Sundland

1
@MikaS 아 그래. 당신이 말한 것처럼 나는 DB에 연결하고있었습니다. 우리가 한 번 연결하고 db 변수를 재사용 할 수 있다는 것을 몰랐습니다. 정말 고맙습니다.
ozgrozer

1
큰 대답; 시간이 밖으로 빨아 된 계산, 나는 RTFM을 기억해야한다
Mr.Budris

그래서 같은 클라이언트를 구현했지만 같은 문제가 (db.collection는 함수가 아닙니다) 거기에 여전히 내부 \ node_modules \ MongoDB를 \ lib 디렉토리 \ gridfs 스트림 \하는 index.js : 50 : 27
alex351

34

^ 3.0.1 버전을 계속 사용하려는 경우 MongoClient.connect()메소드 사용 방법의 변경 사항을 알고 있어야합니다 . 콜백은 db대신 반환하지 않습니다. client이 함수 에는 찾고자 db(dbname)하는 db인스턴스 를 얻기 위해 호출해야하는 함수 가 있습니다 .

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

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

2
이 답변은 최신 버전이며 드라이버 버전 3에 적용됩니다. 감사합니다
Mohammad

1
이 솔루션을 권장합니다. 나중에 참조하기에 더 적합합니다.
Jamie Nicholl-Shelley

31
MongoClient.connect(url (err, client) => {
    if(err) throw err;

    let database = client.db('databaseName');

    database.collection('name').find()
    .toArray((err, results) => {
        if(err) throw err;

        results.forEach((value)=>{
            console.log(value.name);
        });
    })
})

코드의 유일한 문제점은 데이터베이스 핸들러를 보유하고있는 오브젝트에 액세스한다는 것입니다. 데이터베이스에 직접 액세스해야합니다 (위의 데이터베이스 변수 참조). 이 코드는 데이터베이스를 배열로 반환 한 다음 반복하여 데이터베이스에있는 모든 사람의 이름을 기록합니다.


이 답변은 길이와 내용으로 인해 품질이 낮은 것으로 표시됩니다. 자세한 정보를 제공하십시오.
Wahyu Kristianto 2016 년

필요한만큼만 있으면됩니다. 이 답변이 도움이되었습니다.
마누엘 에르난데스

1
@ManuelHernandez 그것이 도움이 된 것을 기쁘게 생각합니다 :)
Dre Jackson

이것은 올바른 대답입니다. 이것을 올바른 an으로 표시하십시오.
Ninad Kambli

12

Mongo Client v3.x에 대한 @MikkaS 답변에 대한 돼지 뒷받침, async / await 형식이 필요했습니다.이 형식은 다음과 같이 약간 수정되었습니다.

const myFunc = async () => {

     // Prepping here...


    // Connect
    let client = await MongoClient.connect('mongodb://localhost');
    let db = await client.db();

    // Run the query
    let cursor = await db.collection('customers').find({});

    // Do whatever you want on the result.
}

7

데이터베이스 이름을 URL의 일부로 유지할 수 있는지 확인하기 위해 약간의 실험을 수행했습니다. 나는 약속 구문을 선호하지만 여전히 콜백 구문에서 작동해야합니다. client.db ()는 매개 변수를 전달하지 않고 호출됩니다.

MongoClient.connect(
    'mongodb://localhost:27017/mytestingdb', 
    { useNewUrlParser: true}
)
.then(client => {

    // The database name is part of the url.  client.db() seems 
    // to know that and works even without a parameter that 
    // relays the db name.
    let db = client.db(); 

    console.log('the current database is: ' + db.s.databaseName);
    // client.close() if you want to

})
.catch(err => console.log(err));

내 package.json은 monbodb ^ 3.2.5를 나열합니다.

지원 중단 경고를 처리하려는 경우 'useNewUrlParser'옵션이 필요하지 않습니다. 그러나이 시점에서 새 드라이버가 기본값이되고 더 이상 옵션이 필요하지 않은 버전 4가 나올 때까지 사용하는 것이 좋습니다.


5

이 코드를 실행하여 쉽게 해결했습니다.

 npm uninstall mongodb --save

 npm install mongodb@2.2.33 --save

행복한 코딩!


4

코드 아래에 mongoclient를 사용하는 MongoDB 셸 버전 v3.6.4가 있습니다.

var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var url = 'mongodb://localhost:27017/video';
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, client) 
{
assert.equal(null, err);
console.log("Successfully connected to server");
var db = client.db('video');
// Find some documents in our collection
db.collection('movies').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc.title);
});
// Close the DB
client.close();
});
// Declare success
console.log("Called find()");
 });

이 질문은 쉘이 아닌 노드 드라이버와 관련이 있습니다.
UpTheCreek

3

누군가이 오류를 해결하는 방법을 여전히 시도하고 있다면 아래와 같이 수행했습니다.

const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mytestingdb';

const retrieveCustomers = (db, callback)=>{
    // Get the customers collection
    const collection = db.collection('customers');
    // Find some customers
    collection.find({}).toArray((err, customers) =>{
        if(err) throw err;
      console.log("Found the following records");
      console.log(customers)
      callback(customers);
    });
}

const retrieveCustomer = (db, callback)=>{
    // Get the customers collection
    const collection = db.collection('customers');
    // Find some customers
    collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
        if(err) throw err;
      console.log("Found the following records");
      console.log(customers)
      callback(customers);
    });
}

const insertCustomers = (db, callback)=> {
    // Get the customers collection
    const collection = db.collection('customers');
    const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
    // Insert some customers
    collection.insertMany(dataArray, (err, result)=> {
        if(err) throw err;
        console.log("Inserted 3 customers into the collection");
        callback(result);
    });
}

// Use connect method to connect to the server
MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
  console.log("Connected successfully to server");
  const db = client.db(dbName);
  insertCustomers(db, ()=> {
    retrieveCustomers(db, ()=> {
        retrieveCustomer(db, ()=> {
            client.close();
        });
    });
  });
});

이 솔루션과 @Dre Jackson은 07/2020부터 노드와 함께 작동하는 솔루션입니다. connect 콜백에 인수로 전달되는 것은 db가 아닌 MongoClient이므로 db를 가져와야합니다. 그 useUnifiedTopology: true외에도이 솔루션에는 요즘에도 필요한을 나열합니다.
Coffee_fan

1

MongoDB 쿼리는 커서를 메모리에 저장된 배열로 반환합니다. 해당 배열의 결과에 액세스하려면 .toArray()쿼리 끝에서 호출해야합니다 .

  db.collection("customers").find({}).toArray() 
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.