Mongoose import from file "buffering timed out" - javascript

I'm trying to import some .json data to mongo, but when trying to save() a person, it just waits some seconds and then crashes with an error: MongooseError: Operation people.insertOne() buffering timed out after 10000ms
It's weird, because when I'm doing POST request it works fine, the person is added correctly.
I wrote some console.logs for help, and it prints the person correctly (inside for loop).
My import script file:
const fs = require('fs/promises')
const express = require('express')
const Person = require('../models/people')
const router = express.Router()
const importData = async () => {
const data = await fs.readFile('./people.json')
console.log(data)
const dataParsed = JSON.parse(data)
for(const person of dataParsed) {
const personToSave = new Person({
firstName: person.firstName,
lastName: person.lastName
})
console.log(personToSave)
await personToSave.save()
}
}
importData()
module.exports=router
My connect:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const people = require('./routers/people');
const pets = require('./routers/pets');
const aggregate = require('./routers/aggregate');
const port = 3000;
app.use(express.json());
app.use('/people', people);
app.use('/pets', pets);
app.use('/aggregate', aggregate);
mongoose.connect('mongodb://localhost:27017/people').then(() => {
console.log('Connected to mongoDB');
app.listen(port, () => {
console.log(`App is listening at port ${port}`);
});
});

Related

Error: Route.get() requires a callback function but got a [object Undefined] in Node.js

I am getting the Error: Route.get() requires a callback function but got a [object Undefined]
while running my app.js file. I am following the freecodecamp tutorial "4 nodejs project", the
error is in task manager app.
my app.js
const express = require('express')
const app = express()
const tasks = require('./routes/tasks') //middleware
app.use(express.json())
//routes app.get('/hello',(req,res) => {
res.send('task manager app')
})
app.use('/api/v1/tasks',tasks)
const port = 3000
app.listen(port,console.log(Server is listening on port ${port}...))
routes/tasks.js
const express = require('express')
const router = express.Router()
const { getAllTasks,
createTask,
getTask,
updateTask,
deleteTask, } = require('../controllers/tasks')
router.route('/').get(getAllTasks).post(createTask)
router.route('/:id').get(getTask).patch(updateTask).delete(deleteTask)
module.exports = router
controllers/tasks.js
const getAllTasks = (req,res)=\> {
res.send('all items')
}
const createTask = (req,res) =\> {
res.send('create task')
}
const getTask = (req,res) =\> {
res.send('get single task')
}
const updateTask = (req,res) =\> {
res.send('update task')
}
const deleteTask = (req,res) =\> {
res.send('delete task')
}
module.export = {
getAllTasks,
createTask,
getTask,
updateTask,
deleteTask,
}
no error should be there but throws the above error.
You are trying to get your controller function in your root for more details you can check out here moz
router.get('/',getAllTasks) //example

how to get all of registered users

How can I get all the registered users in my course-booking system?
this is my controllers user.js
const User = require("../models/User") //import user model
const bcrypt = require("bcrypt") //import bcrypt
const auth = require("../auth")
module.exports.getAllUsers = (params) => {
return User.find(params.userId).then(resultFromFind => {
return resultFromFind
})
}
and this is my routes user.js
const express = require("express")
const router = express.Router()
const UserController = require("../controllers/user")
const auth = require("../auth")
router.get('/all', auth.verify, (req, res) => {
const users = auth.decode(req.headers.authorization)
UserController.getAllUsers().then(user => res.send(user))
})
I don't know why I get this error on my console.. please help
GET http://localhost:3000/api/users/all 500 (Internal Server Error)
You need to pass the params as a parameter of getAllUsers()
const express = require("express")
const router = express.Router()
const UserController = require("../controllers/user")
const auth = require("../auth")
router.get('/all', auth.verify, (req, res) => {
const users = auth.decode(req.headers.authorization)
UserController.getAllUsers(req.params).then(user => res.send(user)) // <------------------------
})

Client.db is not defined (MongoDB backend API) error

I'm trying to get data from a collection in my MongoDB backend and keep running into an error that my client is not defined. I was wondering if anyone has encountered this, and what needs to be added to make this work?
Error:
Client is not defined.
const db = client.db('products');
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const user = require("./routes/user");
const cors = require('cors');
const MongoClient = require('mongodb').MongoClient;
const mongo_uri = 'mongodb+srv://***:***#cluster0.fetfl.gcp.mongodb.net/*****?retryWrites=true&w=majority';
const db = client.db('products')
const collection = db.collection('brand')
MongoClient.connect(mongo_uri, { useNewUrlParser: true })
.then(client => {
console.log('connected');
const db = client.db('products');
const collection = db.collection('brand');
app.listen(port, () => console.info(`REST API running on port ${port}`));
}).catch(error => console.error(error));
app.get('/', (req, res) => {
db.collection('brand').find().toArray().then(results => {
console.log(results)
})
.catch(error => console.error(error))
})
I believe you do not have client defined. What you do have defined is MongoClient.
So probably, the code that you are looking for is:
const db = MongoClient.db('products')
The client objects itself is not defined.

NodeJS - Return always pending, but console.log shows correct data

I am having a hard time understanding, why my Async function correctly logs data from Database, but when I want to return the data, it always: Promise { pending }.
Here's my getUsers.js:
const express = require('express');
var router = ('express-promise-router');
const config = require('../../config/config.json');
const { Pool } = require('pg');
const pool = new Pool({
user: config.database.username,
host: config.database.ip,
database: 'portal',
password: config.database.password,
port: config.database.port,
})
async function getUsers(){
await pool.connect();
const res = await pool.query('SELECT * FROM usr.users');
//console.log(res);
return res;
await pool.end();
}
module.exports = getUsers;
I tried almost every type of async function (no matter if promise or callback) and I always get correct data immediately when I try to console.log(res). But when I try to return res -> I get Promise { < pending > }
Here is the index.js where I call this middleware function:
const config = require('./config/config.json');
const express = require('express');
var router = express.Router();
const axios = require('axios');
//const getTasks = require('./middleware/getTasks');
const getUsers = require('./middleware/pgsql/getUsers');
const users = require('./routes/users');
const app = express();
//app.use(getTasks);
app.use(getUsers);
app.use('/api/users', users);
const allusers = getUsers();
console.log(allusers);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port: ${port}...`));
No matter what I try, I am unable to retrieve my users array in index.js. I am using npm PG and postgress sql database. What am I missing?

Route.delete() requires a callback function but got a [object Object]

I have node-express app where I have bunch of Routes for login, logout and signup and one Route for checking authorised Route which can be accessed only through providing authToken. I moved the Routes to separate Route file and I got the above error.
This is my Users Routes File:
const express = require('express');
const authenticate = require('./../middleware/authenticate');
const router = express.Router();
const {User} = require('./../models/user');
router.post('/',(req, res) => {
var body = _.pick(req.body,['email','password']);
var user = new User(body);
user.save().then(() => {
return user.generateAuthToken()
}).then((token) => {
res.header('x-auth', token).send(user);
}).catch((e) => {
res.status(400).send(e);
});
});
router.post('/login',(req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByCredentials(body.email, body.password).then((user) => {
return user.generateAuthToken().then((token) => {
res.header('x-auth', token).send(user);
});
}).catch((e) => {
res.status(400).send(e);
});
});
router.delete('/logout',authenticate, (req, res) => {
req.user.removeToken(req.token).then(() => {
res.status(200).send();
},(e) => {
res.status(400).send(e);
}) ;
});
router.get('/me',authenticate, (req,res) => {
res.send(req.user);
});
module.exports = router;
Following is my main server.js file:
const express = require('express');
const _ = require('lodash');
var app = express();
const usersRoutes = require('./routes/users');
app.use(express.json());
app.use('/users', usersRoutes);
var {mongoose} = require('./db/mongoose');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');
const port = process.env.PORT || 3000 ;
app.listen(port, () => console.log(`Listening on ${port}...`))
I have a model/Schema(mongoose) file for User so If You feel you need that I am ready to edit my question. Thanks.
The problem is that router.delete is expecting a function on the middleware parameter (like you did in your server.js file with app.use(express.json())) so it can be used like a callback which gets called whenever a request reach your route.
Try changing authenticate to authenticate().
It seems like in your users routes file you are importing the entire module who contains the authenticate function, so when try to access it like a function you'll get an error. You need to import it like you did in your server.js file.
Change the line const authenticate = require('./../middleware/authenticate'); for const {authenticate} = require('./../middleware/authenticate');.

Categories