Connect mangoDB Atlas with nodejs - javascript

I can't connect to MongoDB database, yet I tried everything ! I have successfully replaced the password.
const mongoose = require("mongoose");
mongoose
.connect(
"mongodb+srv://vibess:0KksWIBp6slcBLm0#cluster0.iuvoi.mongodb.net/?retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}
)
.then(() => console.log("Connected !!"))
.catch(() => console.log("Not connected!"));
Here is the Database
MangoDB

You will need another function to complete the operation. the function is usually called run then you need to write all the operations of your server in the scope of this function. here is an example of a server of mine Also you need to declare the name of your database before text retrywrites=true
//connect to mongodb
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#cluster0.qtoag.mongodb.net/Teletale?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function run() {
try {
await client.connect((err) => {
const db = client.db("Teletale");
const djiPackages = db.collection("Devices");
const bookingsCollection = db.collection("bookings");
const testimonialCollection = db.collection("testimonials");
const usersCollection = db.collection("users");
// ==============GET API ====================
//GET API
app.get("/", (req, res) => {
res.send("Welcome to Teletale");
});
//GET API (dji Package)
app.get("/Devices", async (req, res) => {
const result = await djiPackages.find({}).toArray();
res.send(result);
});
//GET API (users)
app.get("/users", async (req, res) => {
const result = await usersCollection.find({}).toArray();
res.send(result);
});
// verify admin data form database
app.get("/users/:email", async (req, res) => {
const email = req.params.email;
const query = { email: email };
const user = await usersCollection.findOne(query);
let isAdmin = false;
if (user?.role === "admin") {
isAdmin = true;
}
// localhost:5000/users/admin#admin.com will show true
res.json({ admin: isAdmin });
});
//GET API (Bookings)
app.get("/bookings", async (req, res) => {
let query = {};
const email = req.query.email;
if (email) {
query = { email: email };
}
const result = await bookingsCollection.find(query).toArray();
res.send(result);
});
//GET Dynamic (Bookings)
app.get("/bookings/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await bookingsCollection.findOne(query);
res.send(result);
});
//GET Dynamic (products)
app.get("/Devices/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await djiPackages.findOne(query);
res.send(result);
});
//GET (testimonials)
app.get("/testimonials", async (req, res) => {
const result = await testimonialCollection.find({}).toArray();
res.send(result);
});
// ==========================POST API=========================
//POST API (dji Package)
app.post("/Devices", async (req, res) => {
const newTours = req.body;
const result = await djiPackages.insertOne(newTours);
res.send(result);
});
//POST API (users)
app.post("/users", async (req, res) => {
const user = req.body;
const result = await usersCollection.insertOne(user);
console.log(result);
res.send(result);
});
//POST API (Bookings )
app.post("/bookings", async (req, res) => {
const newBooking = req.body;
const result = await bookingsCollection.insertOne(newBooking);
res.send(result);
});
//POST API (Testimonials )
app.post("/testimonials", async (req, res) => {
const newBooking = req.body;
// console.log(newBooking);
const result = await testimonialCollection.insertOne(newBooking);
res.send(result);
});
// ======================DELETE API ========================
//DELETE API(Bookings)
app.delete("/bookings/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await bookingsCollection.deleteOne(query);
res.send(result);
});
//DELETE API(drone)
app.delete("/Devices/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await djiPackages.deleteOne(query);
res.send(result);
});
// =================Update API====================
app.put("/bookings/:id", async (req, res) => {
const id = req.params.id;
const newStatus = req.body;
const query = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
data: newStatus.newData,
},
};
const result = await bookingsCollection.updateOne(
query,
updateDoc,
options
);
res.send(result);
});
//upsert Google user data
app.put("/users", async (req, res) => {
const user = req.body;
const filter = { email: user.email };
const options = { upsert: true };
const updateDoc = { $set: user };
const result = await usersCollection.updateOne(
filter,
updateDoc,
options
);
res.json(result);
});
// add admin role
app.put("/users/admin", async (req, res) => {
const user = req.body;
const filter = { email: user.email };
const updateDoc = { $set: { role: "admin" } };
const result = await usersCollection.updateOne(filter, updateDoc);
res.json(result);
});
});
} finally {
// await client.close();
}
}

Related

Await function doesn't work with mongo DB collections

I'm having trouble capturing the current collection in mongodb.
I have a file with FetchUsers function which returns a collection with users:
const mongoose = require('mongoose');
const uri = "mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const fetchUsers= () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try{
mongoose.connect(uri);
} catch (error)
{
console.log(error);
}
const collectionName = 'UsersTests'
const Users = mongoose.model(collectionName, new mongoose.Schema({}));
Users .find({}, function(err, docs) {
if (err) {
console.error(err);
return;
}
console.log(`Documents in ${collectionName}:`);
mongoose.connection.close();
console.log(`My current collection: ${docs}`);
return docs;
});
}
module.exports = fetchUsers
In another file I have a function that takes the returned value and then displays it:
const fetchData = require("../../controllers/USersControllers/fetchUsers.js");
async function displayUsers() {
let users = await fetchData();
console.log(users);
}
module.exports = displayUsers;
and all this is running on the express server
const express = require("express");
const displayUsers = require("./public/js/displayUsers.js");
const app = express();
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.listen(5000, () => {
console.log("Server started on port 3000");
displayUsers();
});
The problem is that displayUsers displays undefined and doesn't wait until fetchData returns a collection.
OK, I corrected the code and it works.
GetUsersModel.js:
const mongoose = require("mongoose");
const uri =
"mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
try {
mongoose.connect(
uri
);
console.log("Database conected!");
} catch (error) {
console.log(error);
console.log("Database connection failed");
}
const Schema = new mongoose.Schema({
content: String,
title: String,
author: String,
});
const Users =
mongoose.model.userTest ||
mongoose.model("userTest", Schema);
module.exports = Users;
fetchUsersData.js
const mongoose = require('mongoose');
const Users =
require("../controllers/SnippetsControllers/GetSnippetModel.js");
const uri =
"mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const fetchUsers = () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try{
mongoose.connect(uri);
console.log('Database conected!!!!!')
} catch (error)
{
console.log(error);
console.log('Database connection failed')
}
return new Promise((resolve, reject) => {
Users.find({}, function(err, docs) {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
});
}
module.exports = fetchUsers;
UseUsersData.js
const fetchData = require("../models/fetchUsersData");
async function displayUsers(req) {
let usersContainer = [];
try {
let users = await fetchData();
let usersArray = users;
console.log(usersArray);
} catch (error) {
console.log(error);
}
}

BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

I built a crud application using mern stack. Then I tried the search operation for the application but it show me this error:
BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
This is my client side code:
Search.js
import React from 'react';
const Search = () => {
const searchHandle = e => {
e.preventDefault();
const userName = e.target.search.value;
fetch(`http://localhost:5000/user/${userName}`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
console.log(typeof(userName));
}
return (
<div className='px-3 py-2 w-3/4'>
<h1 className='text-3xl font-bold mb-3'>Search User:</h1>
<form onSubmit={searchHandle}>
<input className='bg-gray-200 rounded p-2 w-3/4' type="search" name="search" id="name" />
<button className='bg-blue-500 mx-2 py-2 px-4 rounded' type='submit'>Search</button>
</form>
</div>
);
}
export default Search;
This is my server side code:
const expres = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const app = expres();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(expres.json())
const uri = "mongodb+srv://user:##cluster0.moilkdv.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
async function run() {
try {
const userCollection = client.db('simpleNode').collection('users');
// get all users
app.get('/user', async (req, res) => {
const cursor = userCollection.find({});
const users = await cursor.toArray();
res.send(users);
})
// get a specific user for update
app.get('/user/:id', async (req, res) => {
const updateId = req.params.id;
const updateQuery = { _id: ObjectId(updateId)}
const user = await userCollection.findOne(updateQuery);
res.send(user);
})
// updating user
app.put('/user/:id', async (req, res) => {
const userId = req.params.id;
const user = req.body;
const filter = { _id: ObjectId(userId) };
const options = { upsert: true };
const updatedUser = {
$set: {
name: user.name,
address: user.address
}
}
const result = await userCollection.updateOne(filter, updatedUser, options);
res.send(result);
})
// creating users
app.post('/user', async (req, res) => {
console.log('post api called');
const Nuser = req.body;
const result = await userCollection.insertOne(Nuser);
res.send(result);
});
// search query
app.get('/user/:name', (req, res) => {
const searchName = req.params.name;
console.log(searchName);
})
// deleting user
app.delete('/user/:id', async(req, res) => {
const userId = req.params.id;
const deleteQuery = { _id: ObjectId(userId)};
const resut = await userCollection.deleteOne(deleteQuery);
console.log("Delete complete of: ", userId);
console.log(resut);
res.send(resut);
})
}
finally {
}
}
run().catch(console.dir);
app.get('/', (req, res) => {
res.send('Server is running');
})
app.listen(port);
Please help to solve this error.
That request is sent to app.get('/user/:id') route.
:id or :name is just the name of the parameter.
We have to setup another route for searching, eg: change app.get('/user/:name') to app.get('/user/search/:name')

MVC - Adding Update Functionality to the Model - Node.js Express & MongoDB

I'm developing a Node.js Express & MongoDB web application.
Actually, I'm trying to use the MVC feature. However, there is a problem with my code after that I added the update functionality to the model.
Indeed, when I try to update a post, my application crashes and I get the following error message:
TypeError: C:\Users\DELL\Desktop\node-com4muz-database-mvc\views\admin\posts-list.ejs:19
17| <ol id="posts-list">
18| <% for (const post of posts) { %>
>> 19| <li><%- include('includes/post-item', { post: post }) %></li>
20| <% } %>
21| </ol>
22| <% } %>
C:\Users\DELL\Desktop\node-com4muz-database-mvc\views\admin\includes\post-item.ejs:3
1| <article class="post-item">
2| <h2><%= post.title %></h2>
>> 3| <p class="post-item-author">Rédigé par <%= post.author.name %></p>
4| <p><%= post.summary %></p>
5| <div class="post-actions">
6| <form action="/blog/<%= post._id %>/delete" method="POST">
Cannot read properties of undefined (reading 'name')
at eval ("C:\\Users\\DELL\\Desktop\\node-com4muz-database-mvc\\views\\admin\\includes\\post-item.ejs":15:38)
at post-item (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:703:17)
at include (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:701:39)
at eval ("C:\\Users\\DELL\\Desktop\\node-com4muz-database-mvc\\views\\admin\\posts-list.ejs":29:17)
at posts-list (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:274:36)
at View.exports.renderFile [as engine] (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:491:10)
at View.render (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\express\lib\application.js:657:10)
at Function.render (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\express\lib\application.js:609:3) {
path: 'C:\\Users\\DELL\\Desktop\\node-com4muz-database-mvc\\views\\admin\\posts-list.ejs'
}
Actually, before I changed the code in the model file (see below) and the route file (see below), the update functionality was working fine.
That's the reason why I think we should compare both codes, before and after adding the update functionality to the model, to find where is the issue.
Here is my code before adding the update functionality to the model:
routes\admin\blog.js:
const express = require('express');
const mongodb = require('mongodb');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const db = require('../../data/database');
const Post = require('../../models/post');
const ObjectId = mongodb.ObjectId;
const upload = multer({ storage: storageConfig });
const router = express.Router();
router.get('/posts', async function (req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, 'author.name': 1 })
.toArray();
res.render('posts-list', { posts: posts });
});
router.get('/new-post', async function (req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
});
router.post('/new-post', upload.single('image'), async function (req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
});
router.get('/blog/:id/edit', async function (req, res) {
const postId = req.params.id;
const post = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(postId) },
{ title: 1, summary: 1, content: 1 }
);
if (!post) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
});
router.post('/blog/:id/edit', async function (req, res) {
const postId = new ObjectId(req.params.id);
const result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: postId },
{
$set: {
title: req.body.title,
summary: req.body.summary,
content: req.body.content
// date: new Date()
}
}
);
res.redirect('/posts');
});
router.post('/blog/:id/delete', async function (req, res) {
const postId = new ObjectId(req.params.id);
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: postId });
res.redirect('/posts');
});
router.get('/admin', async function (req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
});
module.exports = router;
models\post.js:
const db = require('../data/database');
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
this.id = id; // may be undefined
}
async save() {
const newPost = {
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
};
const result = await db.getDb().collection('posts').insertOne(newPost);
// console.log(result);
return result;
}
}
module.exports = Post;
And here is the code after adding the update functionality to the model:
routes\admin\blog.js:
const express = require('express');
const mongodb = require('mongodb');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const db = require('../../data/database');
const Post = require('../../models/post');
const ObjectId = mongodb.ObjectId;
const upload = multer({ storage: storageConfig });
const router = express.Router();
router.get('/posts', async function (req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, content: 1, 'author.name': 1 })
.toArray();
res.render('posts-list', { posts: posts });
});
router.get('/new-post', async function (req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
});
router.post('/new-post', upload.single('image'), async function (req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
});
router.get('/blog/:id/edit', async function (req, res) {
const postId = req.params.id;
const post = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(postId) },
{ title: 1, summary: 1, content: 1 }
);
if (!post) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
});
router.post('/blog/:id/edit', async function (req, res) {
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
req.params.id
);
await post.save();
res.redirect('/posts');
});
router.post('/blog/:id/delete', async function (req, res) {
const postId = new ObjectId(req.params.id);
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: postId });
res.redirect('/posts');
});
router.get('/admin', async function (req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
});
module.exports = router;
models\post.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const ObjectId = mongodb.ObjectId;
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
if (id) {
this.id = new ObjectId(id);
}
}
async save() {
let result;
if (this.id) {
result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: postId },
{
$set: {
title: this.id,
summary: this.summary,
content: this.content
}
}
);
} else {
result = await db.getDb().collection('posts').insertOne({
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
});
}
return result;
}
}
module.exports = Post;
You're passing id as a wrong argument to when creating post object under /blog/:id/edit route, it doesn't get picked up, so it saves the post, instead of updating it, making other properties undefined.
Try this, pass 3 undefined arguments before id, which is passed as the last argument under /blog/:id/edit route:
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
...[,,,], // pass 3 undefined arguments
req.params.id
);
await post.save();

React Native Duplicated data in Database

I am new to React Native. I created a Registration App connected to a local PostgreSql Database. I am using Formik for the form, after submitting the form it is recorded in the database. The app refreshes everytime I save the code. However after some refreshes, the data is duplicated in the database. I am using axios and a Rest API. Also using nodemon for the server.
Duplicated Data in the Database
POST REQUEST
const url = 'http://192.168.254.106:5000/users';
handleMessage(null);
handleMessage('Successfully Signed Up!', 'SUCCESS');
try {
const response = await axios.post(url, credentials);
} catch (error) {
handleMessage('An Error Occured.');
}
setSubmitting(false);
}, []);
REST API
const app = express();
const cors = require('cors');
const pool = require('./database');
//middleware
app.use(cors());
app.use(express.json());
//ROUTES
//create user
app.post('/users', async (req, res) => {
try {
const { fullname, email, birthdate, password } = req.body;
const user = await pool.query(
'INSERT INTO users(fullname, email, birthdate, password) VALUES($1, $2, $3, $4) RETURNING *',
[fullname, email, birthdate, password],
);
} catch (err) {
console.error(err.message);
}
});
//get all users
app.get('/users', async (req, res) => {
try {
const allUsers = await pool.query('SELECT * FROM users');
res.json(allUsers.rows);
} catch (err) {
console.error(err.message);
}
});
//get a user
app.get('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const user = await pool.query('SELECT * FROM users WHERE user_id=$1', [id]);
res.json(user.rows);
} catch (err) {
console.error(err.message);
}
});
//update a user
app.put('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const { email } = req.body;
const updateUser = await pool.query('UPDATE users SET email = $1 WHERE user_id=$2', [email, id]);
res.json('Updated!');
} catch (err) {
console.error(err.message);
}
});
//delete a user
app.delete('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const deleteUser = await pool.query('DELETE FROM users WHERE user_id=$1', [id]);
res.json('Deleted!');
} catch (err) {
console.error(err.message);
}
});
app.listen(5000, () => {
console.log('Server is up');
});

Cant get Query by method find() Mongoose

Faced the following problem when I am trying to instantiate a Query using the find method. As a result, I get a query variable containing an object instead of Query and Query's methods are not available to me.
Controller code:
const hModel = require("../models/hModel");
const asyncHandler = require("../middleware/async");
exports.getAll = asyncHandler(async (req, res, next) => {
let query = await hModel.find({ booked: "false" });
query = query.select("location"); // TypeError: query.select is not a function
console.log(query instanceof Query); // false
res.status(200).json({ success: true, data: query });
});
asyncHandler:
const asyncHandler = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
module.exports = asyncHandler;
How can I get this to work properly?
(Posting this after discussion)
The problem was:
Since you await the response from .find({ booked: false }), you already have the "result" instead of "query" in query object. Hence, you will not find the select method on the result (query).
You should wait for the entire query to resolve if that's the intention: const data = await hModel.find({ booked: false}).select('location')
const hModel = require("../models/hModel");
const asyncHandler = require("../middleware/async");
exports.getAll = asyncHandler(async (req, res, next) => {
const resolvedData = await hModel.find({'booked': 'false'})
.select('location');
res.status(200).json({ success: true, data: resolvedData });
});
Try this.
const hModel = require("../models/hModel");
const asyncHandler = require("../middleware/async");
exports.getAll = asyncHandler(async (req, res, next) => {
let query = await hModel.findOne({'booked': 'false'});
console.log("Query Res", query); //make sure you have the right response from db.
query = query.location;
res.status(200).json({ success: true, data: query });
});
Try this:
const hModel = require("../models/hModel");
const asyncHandler = require("../middleware/async");
exports.getAll = async (req, res, next) => {
try {
let query = await hModel.find({'booked': 'false'}, 'location');
res.status(200).json({success: true,data: query});
} catch (error) {
next(error);
}
};

Categories

Resources