I am trying to get a count of products using api calls but in postman its keep loading
router.get(`/get/count`, async (req, res) => {
const productCount = await Product.countDocuments((count)=>count)
if (!productCount) {
res.status(500).json({ success: false });
}
res.send({
productCount: productCount
});
});
(node:28030) UnhandledPromiseRejectionWarning: MongooseError: Query was already executed: Product.countDocuments({})
without async and await also its not working
I try to catch the error and i got this error in postman
{
"success": false,
"error": "Query was already executed: Product.countDocuments({})"
}
code to catch error:
router.get(`/get/count`, (req, res) => {
Product.countDocuments((count)=>count).then((pcount)=>{
if(pcount){
return res.status(200).json({success:true})
}else{
return res.status(404).json({success:false})
}
}).catch((err)=>{
return res.status(400).json({success:false, error:err.message})
})
});
I think in Mongoose operations you want to either await or provide a callback, but not both. Attempting to do both causes it to internally execute the query twice.
Try just:
const productCount = await Product.countDocuments();
If you want to count all the products in your product collection, try this
db.product.countDocuments({})
router.get(`/get/count`, async(req, res) => {
let productCount = await Product.countDocuments();
if(!productCount){
res.send(500).json({success:false})
}
res.send({productCount: productCount})
});
Two way you can do that
Try it you don't need use callback (count)=>count
const express = require('express')
const router = express.Router();
const {Product} = require('../models/products')
const {Category} = require('../models/category')
const catchAsyncErrors = require('../middleware/catchAsyncError')
const mongoose = require('mongoose');
// Get all product
router.get(`/`, async (req, res) => {
let productList = await Product.find().populate('category')
if(!productList) {
res.status(500).json({
success: false
})
}
res.status(200).json({
success: true,
count: productList.length,
productList
});
})
router.get(`/count`, catchAsyncErrors(async(req, res) => {
const countProductList = await Product.countDocuments();
if(!countProductList){
res.status(500).json({
success: false
})
}
res.send({
success: true,
countProduct: countProductList
})
}))
You don't need to include ((count)=>count).
Use Product.countDocuments() instead
Related
I am trying to delete a collection from mongodb using postmap API. Below is my code.The update function is working fine.But, delete function isn't working. It's displaying internal server error.I dont know why?
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//uodate
router.put("/:id", async (req, res) => {
if ((req.body.userId === req.params.id) || req.body.isAdmin) {
if (req.body.password) {
try {
const salt = await bcrypt.genSalt(10);
req.body.password = await bcrypt.hash(req.body.password, salt);
}
catch (err) {
return res.status(500).json(err);
}
}
try {
const user = await User.findByIdAndUpdate(req.params.id, {
$set: req.body,
});
return res.status(200).json("Account has been updated");
}
catch (err) {
return res.status(500).json(err);
}
}
else return req.status(400).json("You can only update your account!!!");
});
//delete
router.delete("/:id", async (req, res) => {
if ((req.body.userId === req.params.id) || req.body.isAdmin) {
try {
await User.deleteOne(req.params.id);
return res.status(200).json("Account has been deleted");
}
catch (err) {
return res.status(500).json(err);
}
}
else return res.status(400).json("You can only update your account!!!");
});
module.exports = router;
Help me with thispostman API screenshot.
Try this:
await User.deleteOne({_id:req.params.id});
You are using deleteOne() method. If you want to delete whole collection, you should use deleteMany() method:
await User.deleteMany({});
The Model.deleteOne method expects a filter object, like {name: "value'"}. You are passing req.params.id which is a string. If you dig out the full text of the error, it will likely complain about that string not being an object.
You probably meant to use the Model.findByIdAndDelete method like
await User.findByIdAndDelete(req.params.id);
I'm trying to call my global variables in my controller but i got an error variable is not defined. Please see the code below for your reference. Hoping to solve my problem. Thank you Guys
**server.js **
const serverConfig = require('./config/server.config')
const app = require('fastify')({ logger: true })
require('./models/response.model')
const mongoose = require('mongoose')
const conn = require('./config/monggo.config')
require('./routes/dbm.routes')(app)
const connect = async () => {
try {
await mongoose.connect(conn.uri)
console.log('Connected to Mongoose!')
} catch (error) {
console.log(error)
}
}
connect();
app.listen(serverConfig.port, '::', (err, address) => {
if (err) {
app.log.error(err)
process.exit(1)
}
console.log('Listening at', address)
})
response.model.js
module.exports = function () {
global.successModel = {
status: 'sucess',
statusCode: 0,
isSuccess: true,
message: ''
}
global.failModel = {
status: 'failed',
statusCode: 1,
isSuccess: false,
message: 'Error encountered while processing request.'
}
}
**monggo.controller.js
**
exports.getProducts = async (req, res) => {
//find Products in the databse
Product.find({}, (err, product) => {
//send error message if not found
if (err) {
res.send(err);
}
//else pass the Products
res.send(successModel);
})
await res;
}
Hoping to solve my problem. Thank you
The './models/response.model' file exports a function that you need to call to "install" your globals.
- require('./models/response.model')
+ require('./models/response.model')()
As a suggestion, you should avoid to use globals, in fastify you can use:
decorator to add to your app instance useful data such as configs
Moreover, your mongoose connection is unrelated with Fastify, you can encapsulate it into a plugin to be sure that fastify is starting after connecting to the database:
const fp = require('fastify-plugin')
app.register(fp(async function connect (instance, opts) {
await mongoose.connect(conn.uri)
}))
My mongoose model works fine with promises .then() and .catch. However, if I do await User.findOne({ email }), my response test in Postman infinitely awaits.
class UserController
{
...
static async RegisterUser(req, res)
{
...
const doesUserExist = await User.findOne({ email });
if(!doesUserExist)
{
return res.status(400).json({ message: 'User does not exist' });
}
...
}
}
Here is my DB connection if necessary:
const connectDB = async () => {
try {
console.log('Connecting to database...');
const admin = process.env.API_USN;
const adminPassword = process.env.API_PASS;
const options = {
useNewUrlParser: true,
useUnifiedTopology: true
};
const databaseURL = process.env.APP_DB_URL
.replace('<password>', adminPassword)
.replace('<admin>', admin)
.replace('<username>', admin)
console.log(`Connecting to: ${databaseURL}`)
const conn = await mongoose.connect(databaseURL, options);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.log(error);
process.exit(1);
}
};
Anyone know why async/await infinitely waits but .then()/.catch() works perfectly fine? I even tried awaiting User.findOne().exec()
i try to return data in node.js from a APIs , but I'm having problems, because I need an asynchronous function, I couldn't understand for sure the correct use of the promise, I've tried everything and I couldn't put the result in the return, only in the console.log, somebody help me?
const express = require('express')
const MFA = require('mangadex-full-api')
module.exports = {
async indexManga(req, res) {
const mangalist = MFA.login('DarksGol', 'R#ul1605', './md_cache/').then(async () => {
manga = []
await MFA.Manga.search('Kiss').then(results => {
results.forEach((elem, i) => {
let obj = {}
obj.status = elem.status
obj.title = elem.title
manga.push(obj)
})
}).catch(console.error)
return manga
}).catch(console.error)
console.log(await mangalist)
return mangalist
}
}
no error occurred, only infinite loading on request
const express = require('express')
const routes = express.Router()
const searchManga = require('../src/controllers/searchManga')
routes.get('/searchManga', searchManga.indexManga)
module.exports = routes
Looks like indexManga is an endpoint. Each endpoint function must end the request-response cycle by sending a response ( res.send(), res.json(), res.end(), etc). If indexManga s an endpoint, the solution would be:
...
//return mangalist
res.send(mangalist)
or
//return mangalist
res.json({ status: "success", message: "logged in successfully" })
If it is a meddleware:
async indexManga(req, res, next) {
...
//return mangalist
return next()
}
EDIT: you are using async/await with .then() improperly in some places.
Try this way:
module.exports = {
indexManga(req, res) {
MFA.login('DarksGol', 'R#ul1605', './md_cache/').then(() => {
manga = []
MFA.Manga.search('Kiss').then(results => {
results.forEach((elem, i) => {
let obj = {}
obj.status = elem.status
obj.title = elem.title
manga.push(obj)
})
res.json({ status: "success", data: manga })
}).catch((err) => {
res.json({ status: "fail", error: err })
})
}).catch((err) => {
res.json({ status: "fail", error: err })
})
}
}
I don't see why this would cause "infinite loading on request", but you could greatly simplify the code to just
const express = require('express');
const MFA = require('mangadex-full-api');
module.exports = {
async indexManga(req, res) {
await MFA.login('DarksGol', 'R#ul1605', './md_cache/')
const mangaList = [];
const results = await MFA.Manga.search('Kiss');
results.forEach(elem => {
mangaList.push({
status: elem.status,
title: elem.title,
});
});
return mangalist;
},
};
I am trying to find the tasks assigned to the user through this
router.get('/all', auth, async (req, res) => {
try {
const assignments_raw = await Assignment.find({listP: listP.indexOf(req.user.userId)})
res.json(assignments_raw)
} catch (e) {
res.status(500).json({ message: 'Something went wrong, try again' })
}
})
Specifically, this line should have found all the tasks that have an element corresponding to the user ID inside the listP field
const assignments_raw = await Assignment.find({listP: listP.indexOf(req.user.userId)})
But this causes an error, why?
below is an excerpt from Mango
You can do like this
router.get('/all', auth, async (req, res) => {
try {
const assignments_raw = await Assignment.find()
let assignments = []
assignments_raw.map(assignment => {
if (assignment.listP.indexOf(req.user.userId) !== -1) {
assignments.push(assignment)
}
}
)
res.json(assignments)
} catch (e) {
res.status(500).json({ message: 'Something went wrong, try again' })
}
})