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.
Related
I'm trying to make a simple GET request to my localhost:8080.
When I make the GET request with Postman, I set a simple cookie. Now, in the main file, I've:
var express = require('express');
var app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());
const app_router = require('./routes/router');
app.use("/api", app_router);
app.use(express.static('public'));
app.listen(8080, function () {
console.log('Outdoor Localization GNSS middleware.');
});
In routes/router.js I have:
var express = require('express')
const router = express.Router();
const axios = require('axios');
const url = 'http://10.10.0.145:80/api'
router.use(express.json());
router.get('/*', function (request, response) {
console.log(request.Cookie)
axios
.get(request_url)
.then(res => {
console.log(request.Cookie)
})
.catch(error => {
console.error(error)
})
});
The problem is that request.Cookie always return undefined...why is this happening?
you should be accessing the property request.cookies instead of request.Cookie
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}`);
});
});
I am trying to insert a category in the database following the instructions of a course I am taking and I am unable to insert it with the create method. It shows ... loading in Postman and nothing happens and no error message appears on the console. Here are my files.
app.js
const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const expressValidator = require('express-validator')
require('dotenv').config()
//import routes
const authRoutes = require('./routes/auth')
const userRoutes = require('./routes/user')
const categoryRoutes = require('./routes/category')
// app
const app = express()
// db
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true
})
.then(() => console.log('DB Connected'))
// middlewares
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(cookieParser())
app.use(expressValidator())
// routes middleware
app.use('/api', authRoutes)
app.use('/api', userRoutes)
app.use('/api', categoryRoutes)
const port = process.env.PORT || 8000
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
routes/category.js
const express = require('express')
const router = express.Router()
const { create } = require('../controllers/category')
const { requireSignin} = require('../controllers/category')
const { userById } = require('../controllers/user')
router.post('/category/create/:userId', function(req, res){
requireSignin,
create
});
router.param("userId", userById)
module.exports = router
controllers/category.js
const Category = require("../models/category")
const { errorHandler } = require("../helpers/dbErrorHandler")
exports.create = (req, res) => {
const category = new Category(req.body)
category.save((err, data) => {
if(err) {
return res.status(400).json({
error: errorHandler(err)
})
}
res.json({ data })
})
}
models/category.js
const mongoose = require('mongoose')
const categorySchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: true,
maxlength: 32
}
},
{ timestamps: true }
);
module.exports = mongoose.model('Category', categorySchema)
In order to make sure that data is actually being returned, your create function needs to be asynchronous. Adding async/await to the save function should confirm that you are properly saving the data to the database before returning.
It appears you have an error in your route setup. I assume requireSignin and create should be middleware functions.
So instead of
router.post('/category/create/:userId', function(req, res){
requireSignin,
create
});
you should try this
router.post('/category/create/:userId', requireSignin, create);
// assuming 'create' is the last one, since you are ending the request there
// also assuming that 'requireSignin' is setup as middleware, calling next function
As all my requests are working fine, I have a problem with the put. req.body stays empty and then gives that error :
errmsg: "'$set' is empty. You must specify a field like so: {$set:
{: ...}}"
PUT :
router.put('/books/:name', (req, res, next) => {
const localdb = db.client.db(process.env.DB_NAME);
const collection = localdb.collection(process.env.COLL_BOOKS);
collection.replaceOne(
{ "name": req.params.name },
{ $set: req.body },
function (err) {
if (err) throw err
res.status(201).send(true);
});
App.js
const express = require('express'),
app = express();
os = require('os');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./router.js')
require('dotenv').config()
app.use(cors());
app.use(bodyParser.json());
app.use('/api/v1', router);
const port = (process.env.PORT || '3001');
let server = app.listen(port, os.hostname(), () => {
let host = server.address().address,
port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
axios request :
updateItem = newBook => {
Axios.put(process.env.REACT_APP_API_PATH_BOOKS + `${newBook.name}`, newBook)
.then(res => {
this.setState({ newBook: res.data });
this.props.history.push('/admin');
})
.catch(err => console.log(err));
}
I don't understand what I am doing wrong
Make sure you don't have any middlware stripping or incorrectly parsing the body. For instance, you may have a JSON body parser, and not be sending JSON data with JSON application headers.
Can you give a bit of context, in code, for how you are making the put request and also the result of logging the req in a pastebin?
I am trying to serve an angular app using nodejs. But i get this error
"Cannot GET /" in the body of the page. I tried a number of things but still this does not work. do you folks have any suggestion?
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
app.listen(5000, () => console.log('Listening on port 5000'))
////////////////////////////////////////
// View
////////////////////////////////////////
const viewOptions = { include_docs: true }
app.route('/api/schedules').get((req, res) => {
couchDb.getType('schedule', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/stations').get((req, res) => {
couchDb.getType('station', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/tests').get((req, res) => {
couchDb.getType('testConfig', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
you are missing your routes e.g
app.get('/', function (req, res) {
res.send('hello world')
})
or you need to include your all routes through middle ware.
You are getting that error because you are not declaring any endpoints or telling the server to serve anything. It is listening on port 5000, but no responses to any urls have been defined. Here is a piece of example code that will resolve your issue.
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
// This block will make it so that every path on port 5000 responds with "Hello, World!"
app.get('*', (req, res) => {
res.status(200).send("Hello, World!");
});
app.listen(5000, () => console.log('Listening on port 5000'))
This will make it respond with basic text, if you want to serve an angular application, you will need to look into serving static content from express: https://expressjs.com/en/starter/static-files.html
You have to use a routing middleware and map your modules to the required modules.Also make sure your modules are mounted in router instance.
Something like
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
//All requests with /schedules will go to './modules/schedules'
app.use('/schedules', schedules);
app.use('/stations', stations);
app.listen(5000, () => console.log('Listening on port 5000'))
your ./modules/station should look like
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('You are in /station')
})
router.get('/new', function (req, res) {
res.send('You are in /station/new')
})
module.exports = router
For more : https://expressjs.com/en/guide/routing.html