Skip to content

Instantly share code, notes, and snippets.

@manuerumx
Last active August 29, 2015 14:01
Show Gist options
  • Save manuerumx/e2b70b353a1d9ed88404 to your computer and use it in GitHub Desktop.
Save manuerumx/e2b70b353a1d9ed88404 to your computer and use it in GitHub Desktop.
Updating array document with MongooseJS and ExpressJS
var mongoose = require('mongoose');
var myDocument_schema = require('./ObjectModel');
var db_lnk = 'mongodb://localhost/mydatabase';
exports.Update = function (req, res, next){
var db = mongoose.createConnection(db_lnk);
var idDoc = req.param.id; //We get the ID param
var today = new Date();
var myDoc = db.model('MyDocuments',myDocument_schema);
myDoc.findById(idDoc, function(err, doc){
//Update all the fields
doc.someValue : 'This is my new Value';
doc.someDate : today;
doc.someBool : true;
//Now insert at the end of the array
doc.someArray.push({someElement:'Hello', someElement2: "World"});
//Insert at the begining of the array
doc.someArray2.unshift({someElement3:"Foo Bar"});
doc.save(function(err, result){
if(err){
console.log("Ups, something wrong");
}else{
cosole.log("Ok, now what?");
//more code
}
db.close();
});
};
};
var Schema = require('mongoose').Schema;
var myDocumentSchema = new Schema({
someValue : String,
someDate : Date,
someBool : Boolean,
someArray : [{
someElement : String,
someElement2 : String
}],
someArray2 : [{
someElement3 : String
}]
});
module.exports = myDocumentSchema;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment