Mongoose find() 需要几分钟才能 returns latest documents
Mongoose find() takes a few minutes before it returns latest documents
如果我将文档添加到数据库(通过我的应用程序或通过数据库管理工具 RockMongo),我会立即看到文档被添加到数据库(如 RockMongo 所示),没问题。但是,当我在相应的 Mongoose 模型上调用一个简单的 model.find()
时,不会返回对数据库的最新添加。几分钟后他们终于出现了。
看起来文档是从某种 cache/buffer 中读取的,它没有保持更新。我忽略了 Mongoose 中的类似内容吗?
我的后端是这样的:
var mongoose = require('mongoose');
require('./models/Locations');
mongoose.Promise = global.Promise;
mongoose.connect(mongoUrl,{ config: { autoIndex: false } });
var Locations = mongoose.model('Locations');
[...]
app.get('/locations', function(req, res, next)
{
Locations.find(function(err, results)
{
if(err){return res.status(500).json(err);}
res.json(results);
});
});
型号:
var mongoose = require('mongoose');
var LocationsSchema = new mongoose.Schema({
name: String
});
mongoose.model('Locations', LocationsSchema);
如果我在数据库中手动将项目添加到 Locations,并将浏览器指向 /locations,我将在几分钟后才能看到新项目...
改变这个:
Locations.find(function(err, results)
{
if(err){return res.status(500).json(err);}
res.json(results);
});
为此:
Locations.find({},function(err, results)
{
if(err){return res.status(500).json(err);}
res.json(results);
});
已经很久了,但我注意到我从未回答过这个问题,所以我想我可能会以防其他人遇到这个问题。不过,它非常适合我的设置。问题是 Gandi 默认使用具有相对激进设置的缓存引擎 (Varnish),导致我在我的 webapp 中看到的更新缓慢。
要解决这个问题,可以显式设置 header 来停用缓存,例如:
res.setHeader('Cache-Control', 'max-age=0');
如果我将文档添加到数据库(通过我的应用程序或通过数据库管理工具 RockMongo),我会立即看到文档被添加到数据库(如 RockMongo 所示),没问题。但是,当我在相应的 Mongoose 模型上调用一个简单的 model.find()
时,不会返回对数据库的最新添加。几分钟后他们终于出现了。
看起来文档是从某种 cache/buffer 中读取的,它没有保持更新。我忽略了 Mongoose 中的类似内容吗?
我的后端是这样的:
var mongoose = require('mongoose');
require('./models/Locations');
mongoose.Promise = global.Promise;
mongoose.connect(mongoUrl,{ config: { autoIndex: false } });
var Locations = mongoose.model('Locations');
[...]
app.get('/locations', function(req, res, next)
{
Locations.find(function(err, results)
{
if(err){return res.status(500).json(err);}
res.json(results);
});
});
型号:
var mongoose = require('mongoose');
var LocationsSchema = new mongoose.Schema({
name: String
});
mongoose.model('Locations', LocationsSchema);
如果我在数据库中手动将项目添加到 Locations,并将浏览器指向 /locations,我将在几分钟后才能看到新项目...
改变这个:
Locations.find(function(err, results)
{
if(err){return res.status(500).json(err);}
res.json(results);
});
为此:
Locations.find({},function(err, results)
{
if(err){return res.status(500).json(err);}
res.json(results);
});
已经很久了,但我注意到我从未回答过这个问题,所以我想我可能会以防其他人遇到这个问题。不过,它非常适合我的设置。问题是 Gandi 默认使用具有相对激进设置的缓存引擎 (Varnish),导致我在我的 webapp 中看到的更新缓慢。
要解决这个问题,可以显式设置 header 来停用缓存,例如:
res.setHeader('Cache-Control', 'max-age=0');