Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created March 20, 2012 18:40
Show Gist options
  • Save aheckmann/2139497 to your computer and use it in GitHub Desktop.
Save aheckmann/2139497 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var db = mongoose.connect('localhost', 'testing_nestedQueryPositional');
var schemaObjectId = Schema.ObjectId;
/**
* Model: Estimate Line Item
*/
var EstimateLineItemSchema = new Schema({
'name' : String,
'description' : String,
'quantity' : Number,
'cost' : Number
});
//console.log("EstimateLineItemSchema: ", EstimateLineItemSchema);
var EstimateLineItem = db.model('EstimateLineItem', EstimateLineItemSchema);
/**
* Model: Estimate
*/
var EstimateSchema = new Schema({
'name' : String,
'subTotal' : Number,
'finalTotal' : Number,
'creationDate' : { type: Date, default: Date.now },
'status' : { type: String, default: "Active" },
'lineItemSet' : [EstimateLineItemSchema]
});
//console.log("EstimateSchema: ", EstimateSchema);
var Estimate = db.model('Estimate', EstimateSchema);
/**
* Model: Job
*/
var JobSchema = new Schema({
'name' : String,
'description' : String,
'creationDate' : { type: Date, default: Date.now },
'status' : { type: String, default: "Active" },
'scheduleDates' : String,
'customerID' : schemaObjectId,
'estimateSet' : [EstimateSchema]
});
//console.log("JobSchema: ", JobSchema);
var Job = db.model('Job', JobSchema);
mongoose.connection.on('open', function () {
var j = new Job;
j.name = 'first';
j.description = 'blah blah';
j.scheduleDates = 'woooot';
j.estimateSet = [{
name: 'my estimate'
, subTotal: 4
, finalTotal: 3
, lineItemSet: [{
name: 'line item'
, description: 'my line item'
, cost: 3
, quantity: 8
}]
}];
j.save(function (err) {
if (err) console.error(err.stack||err);
Job.update(
{estimateSet: {"$elemMatch": { _id: j.estimateSet[0]._id }}},
{$push:
{
"estimateSet.$.lineItemSet":
{
'name' : 'updated line item name',
'description' : 'updated line item description',
'quantity' : 1,
'cost' : 1
}
}
},
{upsert:false,safe:true},
function (err) {
console.log("Job.update", err);
Job.find(function (err, jobs) {
if (err) console.error(err.stack||err);
console.error(jobs, jobs[0].estimateSet[0].lineItemSet);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
});
}
);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment