1

I want to find the number of visitors. So I just created a collection with the count

 var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Visitor = new Schema({
    count: { type: Number, default: 0 },
});
module.exports = mongoose.model('visitor', Visitor);

Now I want to increment the value of count where the route /backend/visitors is calling

const Visitor = require('../models/Visitor');
router.route('/backend/visitors').get(function (req, res, next) {
    const visitor = new Visitor({
        count:1,
    });
    Visitor.update({}, { __v: 0 })
        .then(users => {
            console.log(users)
            try {
                visitor
                    .save()
                    .then(visitor => {
                        res.send(visitor);
                    })
            }
        }
    )
});

I dont know how to increment a value of count in database, after that i want to send a response of count to the page like res.send(count)

balaji r
  • 31
  • 7

1 Answers1

0

The $inc operator is used for increment or decrement (use a minus sign) operations.

For update operation query, you should refer to the MongoDB docs first: https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/index.html

If the Visitor schema will have only one document, you should be using findOneAndUpdate query. Your query will look like this:

Visitor.findOneAndUpdate({}, {
  $inc: { count: 1 }
}).exec();

If there are multiple documents, you should use updateMany query:

Visitor.updateMany(selectQueryObj, {
  $inc: { count: 1 }
}).exec()
retr0
  • 644
  • 6
  • 16
  • Thank You sir, But its return an error `Unhandled rejection CastError: Cast to number failed for value "{ '$inc': 1 }" at path "count"`, can you help me – balaji r Mar 07 '19 at 04:48
  • I have edited the query. There was a mistake on my part on placement of the `$inc` operator – retr0 Mar 07 '19 at 06:28