Programing

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

lottogame 2020. 7. 20. 21:05
반응형

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


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입니다.


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

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


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();
  });
}); 

For those that want to continue using version ^3.0.1 be aware of the changes to how you use the MongoClient.connect() method. The callback doesn't return db instead it returns client, against which there is a function called db(dbname) that you must invoke to get the db instance you are looking for.

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();
});

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

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

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

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

The only problem with your code is that you are accessing the object that's holding the database handler. You must access the database directly (see database variable above). This code will return your database in an array and then it loops through it and logs the name for everyone in the database.


Piggy backing on @MikkaS answer for Mongo Client v3.x, I just needed the async / await format, which looks slightly modified as this:

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

I solved it easily via running these codes:

 npm uninstall mongodb --save

 npm install mongodb@2.2.33 --save

Happy Coding!


I have MongoDB shell version v3.6.4, below code use mongoclient, It's good for me:

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()");
 });

I did a little experimenting to see if I could keep the database name as part of the url. I prefer the promise syntax but it should still work for the callback syntax. Notice below that client.db() is called without passing any parameters.

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));

My package.json lists monbodb ^3.2.5.

The 'useNewUrlParser' option is not required if you're willing to deal with a deprecation warning. But it is wise to use at this point until version 4 comes out where presumably the new driver will be the default and you won't need the option anymore.


MongoDB queries return a cursor to an array stored in memory. To access that array's result you must call .toArray() at the end of the query.

  db.collection("customers").find({}).toArray() 

참고URL : https://stackoverflow.com/questions/47662220/db-collection-is-not-a-function-when-using-mongoclient-v3-0

반응형