Unhandled promise rejections after UpdateMany using Mongo in NodeJS - node.js

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?

Related

not getting the ops array after inserting into mongo db

when am trying to move the image after inserting into mongo db using the function
var db = require('../config/dbconnect')
module.exports = {
//addProduct:(product,callback)=>
addProduct: (product, callback) => {
//console.log(product)
db.get().collection('product').insertOne(product).then((data) => {
console.log(data)
callback(data.ops[0]._id)
})
}
}
I am getting an error like:
{
acknowledged: true,
insertedId: new ObjectId("61054e43cffb994774d37ab0")
}
(node:6964) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
at E:\Nodejs\ecommerce\helpdesk\product_help.js:11:27
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6964) 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:6964) [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.
This is error first callback. Try the second argument which is the result.
db.get().collection('product').insertOne(product).then((error,data)=>
{
console.log(data)
callback(data.ops[0]._id)
})
instead of callback(data.ops[0]._id).
Try:
db.get().collection('product').insertOne(product).then((data) => {
callback(data.insertedId)
})
.catch((err)=>console.log('venk error',err))
}

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()
})

UnhandledPromiseRejectionWarning: TypeError: res.send is not a function

I am trying to get this aligoapi npm package to work.
when i send request it's showing error
here is my code:
const aligoapi = require('aligoapi');
var AuthData = {
key: '<my_key>',
user_id: '<my_id>',
}
var send = (req, res) => {
console.log('check')
aligoapi.send(req, AuthData)
.then((r) => {
console.log('check1')
res.send(r)
})
.catch((e) => {
console.log('check2')
res.send(e)
})
}
console.log('check3')
var number = {
body: {
sender: '01022558877',
receiver: '01081079508',
msg: 'test msg'
}
}
const result = send(number,'err')
console.log(result)
and this is the terminal output:
justin#Justinui-MacBookPro examples % node test.js
check3
check
undefined
check2
(node:94270) UnhandledPromiseRejectionWarning: TypeError: res.send is not a function
at /Users/justin/Downloads/node.js_exampl/examples/test.js:19:11
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:94270) 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: 3)
(node:94270) [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.
justin#Justinui-MacBookPro examples %
here i notice my request isn't actually being sent because it's returning undefined

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.

mongoose (check and save if new)

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;
}
});

Resources