Zheka Vasil
Zheka Vasil

Reputation: 87

MongoDB does not refresh data automatically?

I use MEAN stack for developing. And after adding some data to MongoDB, the new data is available in front-end only after restarting NodeJS server. There is any way to update MongoDB data 'online'?

This is my API (Node.js):

var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();

mongoose.connect('mongodb://localhost/vt');

var Video = mongoose.Schema({
    idv: String,
    thumbnail: Number,
    aud : String,
    title : String,
    description : String
});
var db;
var video = mongoose.model('video',Video);
video.find({}, function (err, data) {
    db = data;
});

router.get('/api/videos', function (req, res) {
    res.send(db);
});

module.exports = router;

I am adding data via Mongo Shell, it looks like this: db.videos.insert({'idv': '8ifJvMlITNc'}). After that, I get all data from videos table via Ajax. There is no new data in the response from the server until I restart Node.js server

Upvotes: 1

Views: 6061

Answers (1)

Santanu Biswas
Santanu Biswas

Reputation: 4787

In your Node.js app you are fetching the data only once. You are not fetching it when request is received. Change the code to following and you don't have to restart for reading data:

var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();

mongoose.connect('mongodb://localhost/vt');

var Video = mongoose.Schema({
    idv: String,
    thumbnail: Number,
    aud : String,
    title : String,
    description : String
});

var video = mongoose.model('video',Video);

router.get('/api/videos', function (req, res) {
    video.findOne({}, function (err, data) {
        if (err || !data) {
            res.status(500).send();
        }

        res.status(200).send(data);
    });
});

module.exports = router;

Hope this helps.

Upvotes: 2

Related Questions