Skip to content

Instantly share code, notes, and snippets.

@orbitbot
Created May 12, 2014 20:05
Show Gist options
  • Save orbitbot/436ccb66e62bea0a0b99 to your computer and use it in GitHub Desktop.
Save orbitbot/436ccb66e62bea0a0b99 to your computer and use it in GitHub Desktop.
Mongoose 3.8.9 troubleshooting
var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var _ = require('lodash');
var Q = require('q');
var accountSchema = Schema({
username: String,
contacts: [{
account: { type: Schema.Types.ObjectId, ref: 'Account'},
name: String
}]
});
var Account = mongoose.model('Account', accountSchema);
var abeAcc = new Account({ username: 'abe' });
var bobAcc = new Account({ username: 'bob' });
function run() {
Q.ninvoke(abeAcc, 'save').then(function() {
return Q.ninvoke(bobAcc, 'save').then(function(storedAccArray) {
return Q.ninvoke(Account,
'findOneAndUpdate',
{ username: 'abe'},
{ $push: {'contacts': { account: storedAccArray[0]._id, name: 'bob'}}},
{ 'new': true})
.then(function(abeWithContacts) {
// console.log(util.inspect(abeWithContacts));
// console.log(util.inspect(storedAccArray));
var match = _.find(abeWithContacts.contacts, { 'account': storedAccArray[0]._id });
console.log('the next row should print a result');
console.log(match);
var filteredIdMatches = abeWithContacts.contacts.filter(function(arrayElem) {
return arrayElem._id === storedAccArray[0]._id;
});
console.log(util.inspect(filteredIdMatches));
var filteredNameMatches = abeWithContacts.contacts.filter(function(arrayElem) {
return arrayElem.name === storedAccArray[0].username;
});
console.log(util.inspect(filteredNameMatches));
});
});
}).then(function() {
mongoose.connection.close();
}).done();
}
mongoose.connect('mongodb://localhost/troubleshoot');
mongoose.connection.on('open', run);
{
"dependencies": {
"mongoose": "3.8.9",
"lodash": "2.4.1",
"q": "1.0.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment