Skip to content

Instantly share code, notes, and snippets.

@robertdempsey
Last active March 8, 2020 11:18
Show Gist options
  • Save robertdempsey/b5ed0132f46df34f0f59a791dd499001 to your computer and use it in GitHub Desktop.
Save robertdempsey/b5ed0132f46df34f0f59a791dd499001 to your computer and use it in GitHub Desktop.
Pushes an object containing 'saved_at' with today's date, 'saved_by' with a user name into the save_history property
/** create connection pool to system DB in MongoDB
* assume we are using https://www.npmjs.com/package/mongodb
* assume we begin with:
{
system_id: 123,
a: 1,
b: 2,
c: 3
}
*/
system_states_collection.update(
{ system_id: 123 },
{
$set: { a: 4 },
$push: {
save_history: {
saved_at: new Date(),
saved_by: 'SomeUserName'
}
}
}
)
/**
Resulting document:
{
system_id: 123,
a: 4,
b: 2,
c: 3,
{
save_history: [{
saved_at: '2020-03-08T10:27:21.230Z',
saved_by: 'SomeUserName'
}
]
}
}
*/
system_states_collection.update(
{ system_id: 123 },
{
$set: { b: 5 },
$push: {
save_history: {
saved_at: new Date(),
saved_by: 'SomeOtherUserName'
}
}
}
)
/**
Resulting document:
{
system_id: 123,
a: 4,
b: 5,
c: 3,
{
save_history: [
{
saved_at: '2020-03-08T10:27:21.230Z',
saved_by: 'SomeUserName'
},
{
saved_at: '2020-03-09T10:27:21.230Z',
saved_by: 'SomeOtherUserName'
}
]
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment