I have difficult time to get latest bucket documents after any operation (insert/delete). I use node.js + express + couchbase, and here's my code, derived from its official website. it basically just a simple address book web-app and has three function: insert, show or delete contact.
After delete or insert operation, I use res.redirect("\") to reload my page. The problem is: it just show old data, only after I reload it for second time, it shows up. I just don't know what's wrong here. Can anybody help?
/* GET home page. */
router.get('/', function(req, res) {
var query = ViewQuery.from('view_people', 'by_id');
bucket.query(query, function(err, results){
return res.render('index', {people: results});
});
});
/* INSERT Contact here */
router.post('/insert', function(req, res){
var name = req.body.name;
var address = req.body.address;
var job = req.body.job;
var age = req.body.age;
bucket.insert(name, {
name : name,
address : address,
job : job,
age : age
}, function(err, reply){
if(err) return res.send(err);
return res.redirect('/');
})
});
/* REMOVE the contact */
router.get('/remove', function(req, res){
var id = req.query.id;
bucket.remove(id, function(err, response){
if (err) {return res.send(err);}
return res.redirect('/');
})
});
module.exports = router;
In Couchbase, views are eventually consistent and it looks like you are using views, thus the lag you are seeing. You'd be better off getting the document by key if you can, then Couchbase is strongly consistent. You'd get the most performance if you had a meta-data object that is a manual index of all of that user's contacts. Then when you want their contacts, you pull that meta-data object, then do a parallelized bulk get of the objects you want by key. That should perform VERY well and do the exact same thing. On top of that, you have a key pattern that uniquely identifies the object to the user.
Another option is to have a counter object per user that is a key value with just the counter. So For example have a key pattern
username::contacts::counter
Filled out, the object's key might look like
hernandez94::contacts::139
the counter would be the upper bound of the array of contacts for that user. to get the most recent contact, you just get the counter object, take that integer, construct the key and get exactly that object. It'd be very fast. To get all contacts, you get the counter object and then generate the keys to do a parallelized bulk get. Again, that'd be very fast. No querying, just raw speed that scales consistently.
Looks like you need to use stale=false in your view query . See : https://forums.couchbase.com/t/how-does-stale-query-work/870