class MongooseStepByStep {
{
this.uri = anUri;
this.connection = null;
}
{
await this.basicConnect();
}
{
let conn = null;
try {
await mongoose.connect(this.uri);
conn = mongoose.connection;
this.connection = conn;
this.connection
.once('open', () => prn('Success connecting to database'))
.on('error', err => {
prn('ERROR -- ' + err);
});
} catch (err) {
conn && conn.close();
prn(`Error connecting to ${this.uri}`);
prn(`Error: ${err}`);
}
}
{
let mongooseCollection = await this.connection.db.collection(collectionName);
return await mongooseCollection.countDocuments();
}
async showLength(collectionName, dumpLabel) {
prn(`Length (${dumpLabel}): ${await this.lengthOf(collectionName)}`);
}
{
let mongooseCollection = await this.connection.db.collection(collectionName);
await mongooseCollection.deleteMany();
prn(`Removed all from collection "${collectionName}"`);
}
{
let rec;
rec = new Rec();
rec.set('w', 10);
rec.set('h', 2);
await rec.save();
rec = new Rec({ w: 8, h: 7 });
await rec.save();
prn('Done with #addTwoRectangles');
}
{
const models = await Rec.find();
prn('Models (Documents):');
for (let model of models)
prn('Model: ' + model.toString());
}
{
const models = await Rec.find();
prn('Models (Documents):');
for (let model of models)
prn(`Model: ${model.w} x ${model.h}`);
}
{
let models = await Rec.find({w: {$gte: aWidth}});
prn(`Models with w >= ${aWidth}`);
for (let model of models)
prn('Model: ' + model.toString());
}
{
await this.connection.close();
}
{
prn('Starting Demo');
const demo = new MongooseStepByStep('mongodb://localhost:27017/shapes');
await demo.connect();
await demo.showLength('recs', 'Before Remove All');
await demo.removeAllFrom('recs');
await demo.showLength('recs', 'After Remove All');
try {
await demo.addTwoRectangles();
} catch(ex) {
prn('EXCEPTION: ' + ex.toString());
}
await demo.showLength('recs', 'After addTwoRectangles');
await demo.queryAll();
await demo.queryShowingSpecificColumns();
await demo.querySelectWidthGTE(10);
await demo.disconnect();
}
}
MongooseStepByStep.runDemo()
.then(() => prn('Finished Demo'));