mongoose (check and save if new) - node.js

I am getting this error and the request should only be happening once,
UnhandledPromiseRejectionWarning: ParallelSaveError: Can't save() the same doc multiple times in parallel. Document: 5e269bd87c588b6285499c14
at ParallelSaveError.MongooseError [as constructor] (/root/react-passport-example/node_modules/mongoose/lib/error/mongooseError.js:10:11)
at new ParallelSaveError (/root/react-passport-example/node_modules/mongoose/lib/error/parallelSave.js:18:17)
at model.Model.save (/root/react-passport-example/node_modules/mongoose/lib/model.js:434:20)
at /root/react-passport-example/server/routes/public_api.js:64:21
at /root/react-passport-example/node_modules/mongoose/lib/model.js:4590:16
at /root/react-passport-example/node_modules/mongoose/lib/query.js:4351:12
at cb (/root/react-passport-example/node_modules/mongoose/lib/query.js:1900:14)
at result (/root/react-passport-example/node_modules/mongodb/lib/operations/execute_operation.js:75:17) at executeCallback (/root/react-passport-example/node_modules/mongodb/lib/operations/execute_operation.js:68:9)
at handleCallback (/root/react-passport-example/node_modules/mongodb/lib/utils.js:129:55)
at cursor.close (/root/react-passport-example/node_modules/mongodb/lib/operations/to_array.js:36:13) at handleCallback (/root/react-passport-example/node_modules/mongodb/lib/utils.js:129:55)
at completeClose (/root/react-passport-example/node_modules/mongodb/lib/cursor.js:859:16)
at Cursor.close (/root/react-passport-example/node_modules/mongodb/lib/cursor.js:878:12)
at cursor._next (/root/react-passport-example/node_modules/mongodb/lib/operations/to_array.js:35:25) at self._initializeCursor (/root/react-passport-example/node_modules/mongodb/lib/core/cursor.js:750:9) (node:25221) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:25221) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I am wondering if there is a better and cleaner way to do the following.
router.post('/login', (req, res) => {
var query = req.body,
add = new LoginModel(query);
console.log(query.email);
LoginModel.find({uid : req.body.uid}, function (err, docs) {
if (docs.length){
console.log(err);
res.status(200).json({
message: "ERROR USER ALREADY EXISIT",
// user values passed through from auth middleware
//user: req.user
});
}else{
add.save(add.save(function (err, query) {
if (err) return console.error(err);
}));
}
});
});

This is happening because you are using add.save twice in your code. Hope below code works for you.
add.save((err, query) => {
if (err) {
return err;
} else {
return result;
}
});

Related

Mongoose query not running - "cursor.toArray is not a function"

MongoDB beginner, having trouble getting queries to work. Was following a tutorial of sorts and it was a demo notes app. Their syntax for saving new notes works fine.
However when it comes to printing out the list of notes, there seems to be something wrong in the syntax given to me or something im doing wrong.
const mongoose = require("mongoose");
const url =
"mongodb+srv://Saif:<password>#cluster0.8d2lb.mongodb.net/notes-app?retryWrites=true&w=majority";
mongoose.connect(url, {
useNewUrlParser: true,
});
const noteSchema = new mongoose.Schema({
content: String,
date: Date,
important: Boolean,
});
const Note = mongoose.model("Note", noteSchema);
Note.find({}).then((result) => {
result.forEach((note) => {
console.log(note);
});
mongoose.connection.close();
});
After looking up documentation, the actual syntax of find is a little different where they pass in a callback instead of using promises. But changing that block to use a callback still doesnt work
Note.find({}, (error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})
Error
TypeError: cursor.toArray is not a function
at model.Query.<anonymous> (D:\Folders\Documents\CS.........
(Use `node --trace-warnings ...` to show where the warning was created)
(node:27108) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:27108) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
.find method from model returns Query object not Cursor
For cursor you need to do .exec
Note.find({}).exec((error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})

Trying to update a table - Error: Unhandled promise rejection node.js

I'm trying to update a user with a hashed password when I start the app.
So I wrote this in app.js:
try {
bcrypt.hash("ADMIN", saltRounds, async function(err, hash) {
queryUpdate = await Utilisateur.query().patch({
MOTPASS: hash
}).where('NOGENE', 4219)
.catch(console.log('err'));
});
} catch (err) {
errorDbHandler.sendErrorHttp(err, res);
}
And I got this error:
(node:6800) UnhandledPromiseRejectionWarning: TypeError: Utilisateur.query is not a function
at D:\Project\***\backend\app.js:48:37
(node:6800) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6800) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
use this code for catching the error:
try {
bcrypt.hash("ADMIN", saltRounds, async function(err, hash) {
try {
queryUpdate = await Utilisateur.query().patch({
MOTPASS: hash
}).where('NOGENE', 4219);
} catch (e) {
console.log(e);
}
});
} catch (err) {
errorDbHandler.sendErrorHttp(err, res);
}
you tried to mix "then().catch()" with "await", which will not work.

proxyReq.setHeader can not set headers after they are sent

i am building a node.js proxy and i want to add a conditional header
proxy.on('proxyReq', (proxyReq, req, res) => {
const realIP = parseHttpHeader(req.headers['x-real-ip'])[0];
const path = parseHttpHeader(req.headers['x-original-uri'])[0];
pAny([
check_ip(realIP) ,
check_path(path) ,
check_geo(realIP)
]).then(result => {
console.log (result , "result " )
if (result) {
proxyReq.setHeader('namespace' , 'foo');
} else {
proxyReq.setHeader('namespace' , 'bar'); }
console.log('sending req ')
});
});
.
async function check_ip(realIP) {
try {
const result = await ipModel.findOne({ip: realIP}).exec()
console.log(realIP , result , "ip")
if (result) {
return true
} else {
return false
}
} catch (e) {
throw e;
}
}
and it works just fine till i use the methos check_ip then i get the error
(node:3793) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ClientRequest.setHeader (_http_outgoing.js:498:3)
at /home/master/IPS/server.js:109:14
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
(node:3793) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3793) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
as the error clearly states i am handeling a promise in the wrong way but i don't know how to fix it i tried using callbacks i tried using await
make the check_ip return a promise and try
function check_ip(realIP) {
return ipModel.findOne({ ip: realIP }).exec();
}

Unhandled promise rejections after UpdateMany using Mongo in NodeJS

I am using following code for storing documents in mongo db
const MongoClient = require('mongodb').MongoClient
MongoClient.connect(settings.DB_MONGO_CONNECTOR, (err, db) => {
if (err) throw err
this.mongoCollection = db.db(settings.DB_MONGO_TABLE)
.collection(this.mongoTableName)
})
//......
let arr = []
//......
this.mongoCollection.updateMany(arr, (err) => {
if (err) throw err
console.log('Document was saved')
}, { upsert: true })
After call updateMany I am getting error:
(node:8228) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: The update operation document must contain at least one atomic operator.
(node:8228) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Why? Its valid command, or not?

How to handle promise rejection in this case

In here i want to add new field in collection User (User.facebook.botLink)
but i get an error.
Code where i get error looks like this:
app.post('/savelink/', async (req, res, next) => {
try{
console.log("================USER FACEBOOK ===============" + user.local.email)
const {link} = req.body;
console.log(link);
User.update(
{email: user.facebook.email},
{botLink : link},
{multi:true},
function(err, numberAffected){
});
res.status(200).send(link);
}
catch(e){
next(error);
}
});
Error i'm getting:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: error is not defined
(node:6032) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
try this
catch(e){
next(error);
}
to
catch(e){
next(e);
}
You can aslo do a try/catch...finally.
Note that the finally block will be executed regardles of the result of try/catch.
For more einformation, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
try{
// some code
}
catch(error){
// handle error
}
finally {
// do something else
}

Resources