After successful db.collection.update always error is thrown - node.js

Am using Node.JS to update my collection data based on a logic.
The update happens as expected but in my console after the update it is not returning proper values. It is always returning errors. Below is the code snippet
db.collection('test').update(query,operator,options,function(err,docs){
if(errs) {
console.log('something went wrong somewhere');
}
});
The above snippet always prints something went wrong somewhere. Does that mean that the update is not successful.
I use MongoClient along with Node.js.
P.S: Newbie to MongoDB learning via 10gen courses

Related

Cursor.forEach in Express hanging when document not found

I'm using the MongoDB and NodeJS stack trying to do some simple conditional logic. Unfortunately, I am using the MongoDB native driver for NodeJS, and the owner of the project didnt choose to use Mongoose.
The below code is looking through my documents and filtering based on 'props': 'value' and sending a response via Express.
let cursor = db.collection('collection').find({props: 'value' })
cursor.forEach((doc) => {
if (!doc) {
return res.send('No document found with that property assigned!')
}
res.json(doc)
})
The method is working fine when the property is found, but Express hangs when the the value isn't found. Does anyone have any fixes?
It looks like the No document found ... condition will never be triggered. The if block is inside a section of code that will only be executed if the doc variable exists.
Try having the 'no results' condition be a default condition, or check for the cursor to contain documents.

Why does this simple Node, Sequelize Promise code hang?

I'm trying to do a simple command line database transformation with node.js and sequelize. I've simplified my errant code down to the following, but it never returns:
// Set up database connection and models
var models = require('../models_sequelize');
models.User.findOne()
.then(a => {
console.log(a.name);
});
I get a name printed, but then the script hangs. What is wrong? How do I debug this to see what's stuck? I get the impression that there's an orphan promise that's not being fulfilled, but I don't understand where or why. I must be missing something obvious.
If I run the same interactively from the node console, it returns fine.
Sirko's comment re: close() gave me something to go on. I can stop the hanging with the following code:
var models = require('../models_sequelize');
models.User.findOne()
.then(a => {
console.log(a.name);
models.sequelize.close();
})
Alternatively, this seems to work too as I guess it's doing exactly the same thing:
var models = require('../models_sequelize');
models.User.findOne()
.then(a => {
console.log(a.name);
})
.finally(() => {
models.sequelize.close();
});
I also found something about connection pooling timeouts, but I don't think that affects my simple use case. I imagine it'll come into play in more complicated examples.
Would still like to find a good reference as to why this is necessary rather than just my guess.

Mongoose fails insertion for insertMany when a specific index is defined

Mongoose fails to make insertion when the insertMany command is used to insert documents into the database. I have around 2000 documents which I want to insert and instead of saving each one of them one by one I am trying to use the insertMany function for saving it.
If no specific index is defined then it takes a huge time to just save it in the database and if an index is defined the connection gets timed out as soon as the insertion operation takes place.
Model.insertMany(documents, function(batchSaveError, savedDocs) {
if (batchSaveError) {
callback(batchSaveError);
} else {
callback(null);
}
});
This is the code that I am trying to get done.
The issue seemed pretty vague. The connection timeout seemed pretty normal and can happen in any scenario. But whenever the connection times out mongoose tries to reconnect all by itself.
What I was missing was, I was not capturing the error event for the connection safely and that was causing the whole application to crash. Just when I added a proper catch statement for the error event, although it timed out a few times but the insertion went pretty fine and smoot.

Sail. js / Waterline.js - find() not returning array

Problem: I'm getting unexpected output from code that previously worked.
Code Problem:
sails.models.user.find().then(function (users){...});
is currently returning { id: 1 }
but should return an array of User objects like [{id:x, name:y},...]
Code Alterations:
sails.models.user.find().exec(function (err, users){...}); does not contain an error and returns the same as using .then() like above.
sails.models.user.findOne(1).then(function (users){...}); correctly returns a User like {id:x, name:y}.
sails.models.venue.find().then(function (venues){...}); returns an array of venues, just as substituting any other class besides User.
Note:
This code was previously working (it's a pretty simple line), and the only changes I made between it working and not working was running npm install (but it was previously working on heroku where which installed, so I don't think that was a problem) and changing the schema of User to add a few columns (I did this by deleting the User table in the DB, updating the Sails User model, and lifting the app in create mode, so the table exactly matches the model). Neither of these should cause a problem, but we all know how "should" and coding don't mix :P
How do I fix this? And why did this happen? Thanks :)
Realized other code was calling the package sails-mock-models which was doing its job. Totally forgot about that code. Problem solved.

MongoDB does not seem to behave how it should as a whole

When I first used MongoDB I managed to connect successfully, however then I wanted to carry out the most basic query such as:
db.users.find()
I got an error saying TypeError: Cannot read property 'find' of undefined
Basically meaning I cannot use a collection as a property to the object db.
So i tried this:
var user_col = db.collection('users');
user.col.find();
which works absolutely fine.
Over the last few days I have kept having to look up other ways of doing things as the standard documented way doesn't seem to work. Just now I wanted to get the total users on the app, so like it says in the documentation I should do this:
var count = db.runCommand( { count: 'users' } );
console.log(count);
however this gave the error:
TypeError: undefined is not a function
Is there a problem with MongoDB you have seen like this before or am I just being stupid? I do not want to have to keep finding other, less efficient ways of doing things so finally I ask here what is going on.
Thank you.
It appears you are confusing the Mongo shell API with the node.js native driver API. While both are JavaScript, the shell is sync while node.js is async so they're totally different.

Resources