1 válasz

0 szavazat
(6,5e pont) által 
 
Legjobb válasz

Egy ilyen Counter.model.js esetén:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CounterSchema = new Schema({
    counterName: String,
    counterValue: Number
});

module.exports = mongoose.model('Counter', CounterSchema);

Egy ilyen index.js router segíthet:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Counter = require('../models/Counter.model');

var db = 'mongodb+srv://USER:PASS@URL/DATABASE?retryWrites=true&w=majority'
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
router.get('/increase-counter/', function(req, res, next) {
  Counter.findOneAndUpdate(
    {
      counterName: 'name-of-the-counter'
    }, 
    { 
      $inc: { 
        counterValue: 1 
      } 
    }, 
    { 
     upsert: true,
     new: true
    },
    function(err, counter) {
    if (err) {
      console.log(err);
      res.send('error increasing counter', err);
    } else {
     console.log(counter);
     res.send(counter);
    }
  });
});
module.exports = router;
...