Models in ES6
Asynchronous functions on Model return promises, and so are compatible with the ES6 yield keyword and libraries like co.
Note that the functions find(), findOne(), findById(), count(), findOneAndUpdate(), remove(), distinct(), findByIdAndUpdate(), findOneAndRemove(), update(), and findByIdAndRemove() return Query objects, and so you need to use .exec() to use these functions with yield as described above.
create() integrates with co and the yield keyword
co(function*() {
schema = new Schema({
eggs: { type: String, required: true },
bacon: { type: Boolean, required: true }
});
var M = db.model('harmonyCreate', schema, getCollectionName());
var results;
try {
results = yield M.create([
{ eggs: 'sunny-side up', bacon: false },
{ eggs: 'scrambled', bacon: true }]);
} catch(e) {
return done(e);
}
assert.equal(2, results.length);
assert.equal('sunny-side up', results[0].eggs);
assert.equal('scrambled', results[1].eggs);
done();
})();
aggregate() integrates with co and the yield keyword
co(function*() {
schema = new Schema({
eggs: { type: String, required: true },
bacon: { type: Boolean, required: true }
});
var M = db.model('harmonyAggregate', schema, getCollectionName());
try {
yield M.create([
{ eggs: 'sunny-side up', bacon: false },
{ eggs: 'scrambled', bacon: true }]);
} catch(e) {
return done(e);
}
var results;
try {
results = yield M.aggregate([
{ $group: { _id: '$bacon', eggs: { $first: '$eggs' } } },
{ $sort: { _id: 1 } }
]).exec();
} catch(e) {
return done(e);
}
assert.equal(2, results.length);
assert.equal(false, results[0]._id);
assert.equal('sunny-side up', results[0].eggs);
assert.equal(true, results[1]._id);
assert.equal('scrambled', results[1].eggs);
done();
})();
mapReduce() can also be used with co and yield
co(function*() {
schema = new Schema({
eggs: { type: String, required: true },
bacon: { type: Boolean, required: true }
});
var M = db.model('harmonyMapreduce', schema, getCollectionName());
try {
yield M.create([
{ eggs: 'sunny-side up', bacon: false },
{ eggs: 'sunny-side up', bacon: true },
{ eggs: 'scrambled', bacon: true }]);
} catch(e) {
return done(e);
}
var results;
try {
results = yield M.mapReduce({
map: function() { emit(this.eggs, 1); },
reduce: function(k, vals) { return vals.length; }
});
} catch(e) {
return done(e);
}
assert.equal(2, results.length);
assert.ok(results[0]._id === 'sunny-side up' || results[1]._id === 'sunny-side up');
assert.ok(results[0]._id === 'scrambled' || results[1]._id === 'scrambled');
done();
})();