UpdateMany syntax with MongoDB and Node.js - node.js

I can't understand why this code is not changing the database field for all records from "leavetakings" to "TheHike". The database calls and console.logs before and after the statement execute but this appears to do nothing yet causes no errors.
Player.updateMany({location: "leavetakings"},{location: "TheHike"});
I have tried using the $set syntax and async/await functions. Could someone please tell me what silly thing I am doing wrong?

You need to use an atomic operator (such as $set)
The following should work correctly:
Player.updateMany({ location: "leavetakings" }, { $set: { location: "TheHike" } });
Use async/await or a promise to make sure that the query is being executed before the program exits.

Related

Adding a value from Mongoose DB into a variable in Node.js

I am still quite new to Node.js and can't seem to find anything to help me around this.
I am having an issue of getting the query from my last record and adding it to my variable.
If I do it like below: -
let lastRecord = Application.find().sort({$natural:-1}).limit(1).then((result) => { result });
Then I get the value of the variable showing in console.log as : -
Promise { <pending> }
What would I need to do to output this correctly to my full data?
Here is it fixed:
Application.findOne().sort({$natural:-1}).exec().then((lastRecord) => {
console.log(lastRecord); // "lastRecord" is the result. You must use it here.
}, (err) => {
console.log(err); // This only runs if there was an error. "err" contains the data about the error.
});
Several things:
You are only getting one record, not many records, so you just use findOne instead of find. As a result you also don't need limit(1) anymore.
You need to call .exec() to actually run the query.
The result is returned to you inside the callback function, it must be used here.
exec() returns a Promise. A promise in JavaScript is basically just a container that holds a task that will be completed at some point in the future. It has the method then, which allows you to bind functions for it to call when it is complete.
Any time you go out to another server to get some data using JavaScript, the code does not stop and wait for the data. It actually continues executing onward without waiting. This is called "asynchronisity". Then it comes back to run the functions given by then when the data comes back.
Asynchronous is simply a word used to describe a function that will BEGIN executing when you call it, but the code will continue running onward without waiting for it to complete. This is why we need to provide some kind of function for it to come back and execute later when the data is back. This is called a "callback function".
This is a lot to explain from here, but please go do some research on JavaScript Promises and asynchronisity and this will make a lot more sense.
Edit:
If this is inside a function you can do this:
async function someFunc() {
let lastRecord = await Application.findOne().sort({$natural:-1}).exec();
}
Note the word async before the function. This must me there in order for await to work. However this method is a bit tricky to understand if you don't understand promises already. I'd recommend you start with my first suggestion and work your way up to the async/await syntax once you fully understand promises.
Instead of using .then(), you'll want to await the record. For example:
let lastRecord = await Application.find().sort({$natural:-1}).limit(1);
You can learn more about awaiting promises in the MDN entry for await, but the basics are that to use a response from a promise, you either use await or you put your logic into the .then statement.

Dark mongoose magic: "Invalid argument to findOne"

We have several nodejs daemons that make use of mongoose while sharing the same persistence layer (shared module containing the queries).
In one of these daemons (always the same one) we randomly (few times a week) get the following error from mongoose:
mongoose: Invalid argument to findOne()
We've checked all queries and were not able to find out where this might come from. The errors call stack is different every time (no specific mongoose call seems to cause this issue) so we don't think this is specific to the business logic.
In order to do some debugging we added the following logging in case the error happens again:
log({
// What mongoose checks (both false -> the error).
isInstanceOfMQuery: conds instanceof mquery,
isObject: mquery.utils.isObject(conds),
// Trying to find out what this value is.
conds,
toString: Object.prototype.toString.call(conds)
inspect: util.inspect(conds, { showHidden: true, depth: null, showProxy: true })
})
conds is the argument that mongoose is complaining about. log() will JSON.stringify() the whole thing.
This is one of the logs that resulted from this call:
{
"isInstanceOfMQuery": false,
"isObject": false,
"conds": {},
"toString": "[object Null]"
"inspect": "{}",
}
Now this confuses me even more... how can conds be {} and null at the same time?!
Answers I'm looking for:
How can I reproduce this kind of object that conds contains?
How would you proceed with a bug that apparently happens randomly and seldomly?
Is there more we could log in order to identify what kind of value conds has or where it comes from?
Any ideas appreciated!
This is probably a node bug with the PR to fix here. It's not yet included in a release.
It's not reliably reproducible since it seems to depend on pointers and v8's garbage collection. Just gotta wait for it to be fixed upstream.

mongoose pre update not firing

I have follow the directions in mongoose here
PostSchema.pre('update', function() {
console.log('pre update');
console.log(this);
});
it is not firing this middleware. Am I missing something here?
I have added next so it looks exactly like my pre save, however that still does nothing.
Make sure you don't define this after mongoose.model() has been called. Please also take note that findOneAndUpdate / upserts or updates won't trigger this hook. Another reason why it wouldn't execute is that validation fails. Therefore you would need to setup a pre('validate') hoke
I think you have to add the await keyword before your promise.

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.

Mongoose Model.count() does not run callback as documented

I am following almost the exact example for Model.count() from the Mongoose docs:
User.count({ type: 'jungle' }, function (err, count) {
console.log('I do not ever run');
});
This should print 'I do not ever run'. Instead, it returns a Query object - which should not happen, according to the docs, as I am providing a callback. How can I make the callback function run? Is there some circumstances where the callback is not run?
Using mongoose#3.6.17. Thanks!
Make sure you've connected to the database before calling any model functions. Mongoose will just queue up the count query until you connect otherwise.
See this question of the FAQ.

Resources