TypeError: db.collection이 함수가 아닙니다.
mLab에서 작성한 데이터베이스에 데이터를 올리려고 하는데 오류가 발생하는데 뭐가 잘못됐는지 모르겠어요.저도 이 주제에 대한 질문을 읽어봤지만, 처음이라 제 오류를 해결할 수 없습니다.여기에서는, 실장하려고 하는 코드를 게재하고 있습니다.이 코드는 이 튜토리얼 https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2 에서 발췌한 것입니다.
server.displaces
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.deb.debooks(db.interface)
module.exports = {
url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing"
};
index.displaces를 표시합니다.
const noteroutes = require('./note_routes');
module.exports = function(app,db)
{
noteroutes(app,db);
};
note_module을 클릭합니다.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]);
}
});
});
};
그래서 mongodb 2.2.33으로 내려가는 답변에 투표했는데, 문제 해결을 위해 다운그레이드 하는 것이 이상해서 버전 >= 3.0을 유지할 수 있는 솔루션을 찾았습니다.만약 누군가가 이 문제를 발견했고, 그들의 문제가 승인된 답변과 같은 백지 참조로 전달되지 않았다면, 이 솔루션을 사용해 보십시오.
도망칠 때...
MongoClient.connect(db.url,(err,database) =>{ }
> =3에서는 그 mongodb > = 3.0 입니다.database
로 variable로 입니다.database.collection('whatever')
오브젝트에 , 데이타베이스명을 은, 하는 것입니다.저에게는 다음과 같은 작업이 필요합니다.
MongoClient.connect(db.url,(err,database) =>{
const myAwesomeDB = database.db('myDatabaseNameAsAString')
myAwesomeDB.collection('theCollectionIwantToAccess')
}
이것으로 node.js 서버 실행 중 오류가 수정되었습니다.버전을 다운그레이드하고 싶지 않은 사용자에게 도움이 되었으면 합니다.
(또한 어떤 이유로 db 이름을 모르는 경우 console.log(module)를 실행하면 오브젝트 속성으로 표시됩니다.)
편집(2018년 6월):
이에 따라 콜백은 실제로 데이터베이스 자체 대신 데이터베이스의 연결된 클라이언트를 반환합니다.
따라서 데이터베이스 인스턴스를 가져오려면 이 방법을 사용해야 합니다. 이 방법은dbName
. 에는 '아니다'라고 If not provided, use database name from connection string.
@divysauses 。
', '아까운데'라고 불러야 요.database.db().collection('theCollectionIwantToAccess');
url(' URL)로 database
는 ★★★★client
를 돕기 위해
Mongodb 。 「」의 합니다.2.2.33
mongodb
node_modules
및 add "directory" 를 지정합니다.
"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
PS: @MihirBhende와 @yaxartes 덕분입니다.
참고로
이 필드를 처음 접하는 경우 https://github.com/mongodb/node-mongodb-native/releases, 이외의 릴리스를 선호합니다.
server.js에서는 routes/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 드라이버 모듈이 업데이트 된 것 같습니다.동작하는 문서에서 아래의 코드를 발견했습니다.
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();
});
});
구문 문제가 더 발생할 경우를 대비하여 다음 링크를 참조하십시오.
에서는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★"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])
}
});
});
};
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) => {
...
딜럼 다샤나에게 정말 고마워!당신의 조언이 큰 도움이 되었어요.덧붙이고 싶은 것은, 만약 당신이 약속을 사용한다면, 그것은 다음과 같습니다.
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);
});
당신의 패키지에.json.
다음 버전이 다음과 같은지금은 다음과 같습니다.
"nodemon": "^1.12.1"
"mongodb": "^2.2.33"
위의 nodemon 버전과 mongodb 버전은 오류 없이 함께 작동합니다.그럼 짐은?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.x.x로 이행했습니다.내가 패키지를 바꿨을 때.mogodb npm 모듈의 2.x.x 버전을 요청하기 위한 json 파일. 갑자기 모든 것이 작동되었습니다.
제가 생각한 것은 컬렉션을 다른 오브젝트로 변경하기 위해 모듈이 변경된 것입니다.새 버전을 사용하는 방법은 모르지만 2.x.x 버전을 사용하도록 지정한 경우 이전 방식이 작동합니다.구체적으로는 (제 패키지에서) 확인할 수 있습니다.json 파일, "dependencies" 섹션) "mongodb": "^2.2.31"이 작동합니다.
최적의 방법:
$> npm install mongodb@2.2.31 --save
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err)
//require('./app/routes')(app,{});
//try this
require('./app/routes')(app,database);
app.listen(port,() => {
console.log("We are live on"+port);
});
})
빈 {}에 데이터베이스를 포함해야 합니다.
또는
또한 mongodb를 최신 버전으로 설치하여 문제를 해결할 수도 있습니다.
npm install mongodb@2.2.33 --save
else npm install은 노드 모듈의 "mongodb": "^2.2.33"의 종속성을 추가합니다.
작업 코드 사용:
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_module을 클릭합니다.js
db.collection('notes').insert(note, (err, result) => {
교체하다
db.db().collection('notes').insert(note, (err, result) => {
저는 같은 문제로 같은 튜토리얼을 하고 있습니다.방금 모든 답을 확인했는데 하나 찾았어요.
MongoClient.connect(db.url, { useUnifiedTopology: true }, (err, client) => {
var database = client.db('test');
if (err) return console.log(err)
require('./app/routes')(app, database);
app.listen(port, () => { console.log('We are live on ' + port);}); })
데이터베이스를 클라이언트로 변경하고 데이터베이스를 client.db "test"로 정의합니다.)
언급URL : https://stackoverflow.com/questions/43779323/typeerror-db-collection-is-not-a-function
'programing' 카테고리의 다른 글
참조 오류:Jest 환경이 해체된 후 파일을 '가져오기'하려고 합니다. (0) | 2023.03.18 |
---|---|
Facebook의 앱 내 브라우저가 "net::ERR_FAILED"이지만 다른 브라우저는 없습니다. (0) | 2023.03.18 |
두 객체 어레이를 Angular 2와 TypeScript와 병합하시겠습니까? (0) | 2023.03.18 |
JSON에 의해 시리얼화된 camel Case JSON을 반환하려면 어떻게 해야 합니까?ASP로부터의 NET.NET MVC 컨트롤러 방식 (0) | 2023.03.18 |
"jquery.unoblusive-ajax.js"는 폐지되었습니까? (0) | 2023.03.18 |