Skip to content

Instantly share code, notes, and snippets.

@robertdempsey
Last active March 8, 2020 10:44
Show Gist options
  • Save robertdempsey/6e9e8e9181db84fb38e170ea07eb5bb2 to your computer and use it in GitHub Desktop.
Save robertdempsey/6e9e8e9181db84fb38e170ea07eb5bb2 to your computer and use it in GitHub Desktop.
Will set the property 'created_at' to the current date and time when an existing document is not found
/** create connection pool to system DB in MongoDB
* assume we are using https://www.npmjs.com/package/mongodb
* assume we start with no document with property matching 'system_id: 123'
*/
system_states_collection.update(
{ system_id: 123 },
{
$set: { a: 4 },
$setOnInsert: { created_at: new Date() }
},
{ upsert: true }
)
/**
Resulting document:
{
system_id: 123,
a: 4,
created_at: '2020-03-08T10:27:21.230Z'
}
*/
system_states_collection.update(
{ system_id: 123 },
{
$set: { b: 5 },
$setOnInsert: { created_at: new Date() }
},
{ upsert: true }
)
/**
Resulting document:
{
system_id: 123,
a: 4,
b: 5
created_at: '2020-03-08T10:27:21.230Z'
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment