Db.collection은 MongoClient v3.0 사용 시 함수가 아닙니다.
노드에서 W3schools 튜토리얼을 시도하고 있습니다.JS와 MongoDB.
이 예를 노드에 구현하려고 하면JS 환경에서 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 Enterprise 3.4.4와 MongoDB Node.js 드라이버 v3.0.0-rc0임을 주의해 주십시오.
MongoDB 네이티브 NodeJS 드라이버 버전 3.0을 사용하는 사용자:
(이것은, 「mongodb」(^3.0.0-rc0」) 또는 그 이후의 버전의 패키지가 있는 사람에게 적용됩니다.최신 버전을 계속 사용하려는 경우)
MongoDB 네이티브 NodeJS 드라이버 버전 2.x에서는 connect callback의 인수로서 database 객체를 얻을 수 있습니다.
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();
});
});
저도 같은 일을 겪었습니다.포장되어 있습니다.json, mongodb 행을 "mongodb"로 변경합니다: "^2.2.33".이 버전을 설치하려면 MongoDB Driver/node_modules 등을 삭제하여 mongodb npm을 제거한 후 npm을 설치해야 합니다.
이것으로 문제가 해결되었습니다.버그나 문서를 업데이트해야 할 것 같습니다.
버전 ^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();
});
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);
});
})
})
코드의 유일한 문제는 데이터베이스 핸들러를 보유하고 있는 오브젝트에 액세스하고 있다는 것입니다.데이터베이스에 직접 액세스해야 합니다(위의 데이터베이스 변수 참조).이 코드는 어레이로 데이터베이스를 반환하고 데이터베이스를 루프하여 데이터베이스에 있는 모든 사용자의 이름을 기록합니다.
Mongo Client v3.x의 @MikkaS 응답에 대한 피기백입니다.비동기 / 대기 포맷이 필요했습니다.이 형식은 다음과 같이 약간 변경되었습니다.
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.
}
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));
제 소포요.json에는 monbodb ^3.2.5가 표시됩니다.
권장 해제 경고를 처리하려는 경우 'useNewUrlParser' 옵션은 필요하지 않습니다.그러나 이 시점에서 버전4가 나올 때까지 사용하는 것이 좋습니다.이 버전4에서는 새로운 드라이버가 디폴트로 되어 옵션이 필요 없게 될 가능성이 있습니다.
이전 버전의 MongoDb 클라이언트 2.2.33에서 동작했습니다.
옵션 1: 이전 버전을 사용할 수 있습니다.
npm uninstall mongodb --save
npm install mongodb@2.2.33 --save
옵션 2: 최신 버전(3.0 이상)을 계속 사용하고 코드를 약간 수정합니다.
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
if(err) throw err;
let db = client.db('myTestingDb');
db.collection('customers').find().toArray(function(err, result){
if(err) throw err;
console.log(result);
client.close();
});
});
다음 코드를 실행함으로써 쉽게 해결할 수 있었습니다.
npm uninstall mongodb --save
npm install mongodb@2.2.33 --save
해피 코딩!
이 에러의 해결 방법이 아직 남아 있는 경우는, 이하와 같이 실시합니다.
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();
});
});
});
});
아래 코드 use 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()");
});
MongoDB mong mong mongdb mong mong mong mong mong mong mong mong 。어레이의 , 「」에 전화할 가 있습니다..toArray()를 참조해 주세요.
db.collection("customers").find({}).toArray()
답변이 늦었지만 나중에 누군가가 필요할 수도 있습니다.
수집 및 DB 인스턴스를 반환하는 비동기 함수를 만들 수 있습니다.
const dBInstances = async () => {
const collection = await db
.then((client) => {
const db = client.db();
const collection = db.collection("AGGREGATION");
return { collection: collection, db: db };
})
.catch((err) => {
console.log(`Data base instances error ${err}`);
});
return collection;
};
그리고 이 방법으로 dBInstances() 실행 결과를 사용할 수 있게 된 후 아래 예에서 JS 파괴를 사용했습니다.
const test = async (req, res) => {
const { collection, db } = await dBInstances();
console.log(collection);
console.log(db);
};
이제 DB와 컬렉션에 대한 액세스를 분리했습니다.
최근에도 같은 문제가 발생하여 MongoDB 공식 웹사이트 문서와 샘플 코드를 사용하여 해결하였습니다.
MongoDB 클라이언트 버전은 "mongodb"입니다. "^4.4.1" 입니다.그리고 승인된 답변에 따라 MongoDB 패키지를 다운그레이드 할 필요 없이 문서를 삽입할 수 있었습니다.
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.
const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("insertDB");
const haiku = database.collection("haiku");
// create a document to insert
const doc = {
title: "Record of a Shriveled Datum",
content: "No bytes, no problem. Just insert a document, in MongoDB",
}
const result = await haiku.insertOne(doc);
console.log(`A document was inserted with the _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
run().catch(console.dir);
언급URL : https://stackoverflow.com/questions/47662220/db-collection-is-not-a-function-when-using-mongoclient-v3-0
'programing' 카테고리의 다른 글
| TypeError: 'undefined'는 함수가 아닙니다('$(document)' 평가). (0) | 2023.03.21 |
|---|---|
| 커서를 빠르게 이동할 때 마우스 탈퇴 시 반응 이벤트가 트리거되지 않음 (0) | 2023.03.21 |
| extract-text-webpack-plugin React 사용 시 window not defined 오류 발생 (0) | 2023.03.21 |
| RETS MLS 및 RETS 클라이언트 (0) | 2023.03.21 |
| [ spring _ web ]라는 이름의 fragment가 여러 개 발견되었습니다.이것은 상대적인 주문에서는 합법적이지 않습니다. (0) | 2023.03.21 |