ForgeTotal.js 5
it

Total.js 5

Interrogare il database NoSQL

Total.js 5 · total5@0.0.19 nosqldatabasequeries Eseguita con Total.js 5

NOSQL('name').find() restituisce un query builder. Concatena le condizioni e termina con .callback(function(err, response) {}); response è un array di documenti. I metodi più utili:

  • .where('age', '>', 30) confronta un campo (l'operatore predefinito è =; usa >, <, >=, <=, <>)
  • .in('city', ['Bratislava', 'Prague']) corrisponde a uno qualsiasi dei valori
  • .between('age', 20, 40) corrisponde a un intervallo
  • .search('name', 'ann') cerca parole in un campo di testo
  • .sort('age_desc') ordina per un campo (_asc o _desc)
  • .take(10) e .skip(20) impaginano i risultati
  • .fields('name,age') restituisce solo quei campi
  • .first() restituisce un documento invece di un array
controllers/people.js
exports.install = function() {
	ROUTE('POST /seed/', seed);
	ROUTE('GET /older/', older);
	ROUTE('GET /cities/', cities);
	ROUTE('GET /range/', range);
	ROUTE('GET /search/', search);
	ROUTE('GET /page/', page);
	ROUTE('GET /names/', names);
	ROUTE('GET /youngest/', youngest);
};

function seed($) {
	var people = [
		{ id: '1', name: 'Anna Novak', age: 25, city: 'Bratislava' },
		{ id: '2', name: 'Boris Kral', age: 35, city: 'Prague' },
		{ id: '3', name: 'Cyril Dvorak', age: 45, city: 'Vienna' },
		{ id: '4', name: 'Diana Hall', age: 30, city: 'Bratislava' }
	];
	people.wait(function(item, next) {
		NOSQL('people').insert(item).callback(next);
	}, () => $.json({ count: people.length }));
}

function older($) {
	NOSQL('people').find().where('age', '>', 30).sort('age_desc').callback((err, response) => $.json(response));
}

function cities($) {
	NOSQL('people').find().in('city', ['Prague', 'Vienna']).sort('name_asc').callback((err, response) => $.json(response));
}

function range($) {
	NOSQL('people').find().between('age', 26, 40).sort('age_asc').callback((err, response) => $.json(response));
}

function search($) {
	NOSQL('people').find().search('name', 'hall').callback((err, response) => $.json(response));
}

function page($) {
	NOSQL('people').find().sort('age_asc').take(2).skip(2).callback((err, response) => $.json(response));
}

function names($) {
	NOSQL('people').find().fields('name').sort('name_asc').take(2).callback((err, response) => $.json(response));
}

function youngest($) {
	NOSQL('people').find().sort('age_asc').first().callback((err, response) => $.json(response));
}