Matoy Matoy - 4 months ago 27
AngularJS Question

increment counter in node js mongodb

I want to make a counter of how many time the server js file has started, for my website using mongodb driver for angular js.

I want to save a varible named counter which has a value of 0 and then increment that value each time that the server is running. my code is below. as you can see my code doesn't acutally update the field in the db. just the varible.

beside that... well.. the whole code I wrote seems like bad practise. I basically have a document with {id:<>,count:0} and I am looping through all the count fields which are greater the -1 (i.e. integers) although I have only got just 1 count field.

isn't there any simple way to persist/get this 1 value from the db?

How can I update the field inside the db itself using something like $inc, in the easiest way possible?

Thanks

MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
if (err) {
console.log(err);
}
else {
console.log("Connected correctly to DB.");
var dbusers =db.collection('users');
var cursor =dbusers.find( { "count": { $gt: -1 } } );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
doc.count=doc.count+1;
}
}
);
}
db.close();
});

Answer

Try this:

MongoClient.connect(url, function(err, db) {
    if (err) {
        console.log(err);
        return db.close();
    }

    console.log("Connected correctly to DB.");
    // update a record in the collection
    db.users.udpate(
        // find record with name "MyServer"
        { name: "MyServer" },
        // increment it's property called "ran" by 1
        { $inc: { ran: 1 } }
    );
    return db.close();
});

This should be enough to get you started. It sounds like you're trying to do something like: 1. get me all the objects in the collection that have a property 'count' greater than -1 2. increase it's value by 1 3. save it to the collection.

The step you're missing is step 3. Doing it your way you'd have to do a bulk update. The example I gave you is updating a single record.

here is the documentation for increment. And here is the documentation for bulk updates.