Created
February 8, 2016 23:10
-
-
Save kizzlebot/aa17211697fd48cf11c2 to your computer and use it in GitHub Desktop.
Mongoose update via promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Mongoose = require('mongoose'); | |
Mongoose.Promise = require('bluebird'); | |
var Asset = require('./Asset.js')(Mongoose); | |
function createEntry(cb){ | |
var asset1 = new Asset(); | |
var asset2 = new Asset(); | |
asset1.attributes.push({ | |
_field:{ _id:asset2._id, name:'Hostname' }, | |
value: 'antiphates.feralhosting.com' | |
}) | |
return asset1.save(function(err){ | |
if (cb) cb(err, asset1); | |
return asset1; | |
}); | |
return asset1; | |
} | |
function workingUpdater(id){ | |
Asset.find( { _id: id } ) | |
//.populate( { path: 'attributes._field' } ) | |
//.populate( { path: '_partition' } ) | |
.then( doc => { | |
doc[0].attributes[0].value = 'FOO' | |
return doc[0].save(function (err) { | |
if (err) throw new Error(err) | |
console.log('Updated to:',doc[0]) | |
}) | |
}) | |
.catch( err => { throw new Error(err) }) | |
.finally( () => { | |
console.log('close'); | |
//Mongoose.connection.close() | |
}) | |
} | |
function run(){ | |
createEntry(function(err, e){ | |
workingUpdater(e._id.toString()) | |
}); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = Mongoose => { | |
const Schema = Mongoose.Schema | |
const assetSchema = new Schema({ | |
attributes: [{ | |
_field: { | |
type: Schema.Types.ObjectId, | |
ref: 'Field', | |
required: true | |
}, | |
value: { | |
type: Schema.Types.Mixed, | |
required: true | |
} | |
}], | |
_partition: { | |
type: Schema.Types.ObjectId, | |
ref: 'Partition' | |
} | |
}); | |
return Mongoose.model( 'Asset', assetSchema ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment