Я работаю над API входа.
Бэкэнд: Node.JS Хранилище данных: MongoDB
Я получаю TypeError
app.js
:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
var db = require('./db')
db.connect(() => {
app.listen(3000, function (){
console.log(`Listening`);
});
});
const loginRoute = require('./routes/login');
app.use('/login', loginRoute);
Маршрутизатор - login.js
const express = require('express');
const router = express.Router();
const loginSchema = require('../models/LoginSchema');
const db = require('../db');
router.get('/', (req, res) => {
db.collection('login').find({}, function (err, result) {
console.log(result);
res.send('We are at login api'+result);
});
});
router.post('/', (req, res) => {
const logindata = new loginSchema({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
db.collection('login').insert(logindata, function(err, data) {
res.json(data);
});
});
module.exports = router;
Схема: loginschema.js
const mongoose = require('mongoose');
const loginschema = mongoose.Schema({
name: {
type : String
},
email: {
type : String,
required : true
},
password: {
type: String,
require: true
}
});
module.exports = mongoose.model('login', loginschema);
Подключение MongoDB: db.js
const mongoClient = require('mongodb').MongoClient;
const mongoDbUrl = 'mongodb://127.0.0.1:27017';
let db;
function connect(callback){
mongoClient.connect(mongoDbUrl, { useUnifiedTopology: true }, (err, client) => {
db = client.db('test');
callback();
});
}
function get(){
return db;
}
function close(){
db.close();
}
module.exports = {
connect,
get,
close
};
Это ошибка, которую я получаю:
TypeError: db.collection is not a function
at C:\rest-api\routes\login.js:19:8
at Layer.handle [as handle_request] (C:\rest-api\node_modules\express\lib\router\layer.js:95:5)
at next (C:\rest-api\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\rest-api\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\rest-api\node_modules\express\lib\router\layer.js:95:5)
at C:\rest-api\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\rest-api\node_modules\express\lib\router\index.js:335:12)
at next (C:\rest-api\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\rest-api\node_modules\express\lib\router\index.js:174:3)
at router (C:\rest-api\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\rest-api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\rest-api\node_modules\express\lib\router\index.js:317:13)
at C:\rest-api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\rest-api\node_modules\express\lib\router\index.js:335:12)
at next (C:\rest-api\node_modules\express\lib\router\index.js:275:10)
at C:\rest-api\node_modules\body-parser\lib\read.js:130:5
Помощь будет принята с благодарностью