Skip to content

Instantly share code, notes, and snippets.

@AvnerCohen
Created July 25, 2013 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AvnerCohen/6077932 to your computer and use it in GitHub Desktop.
Save AvnerCohen/6077932 to your computer and use it in GitHub Desktop.
Trying to understand how to create a Mongo document, in a nodeJS environment with upsert and $set in the same flow
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/inbox', function(err, db) {
if (err) throw err;
var collection = db.collection('test_insert');
var sample1 = { 'messages.82513': { body: '123\r\n456\r\n789\r\n', db_msg_id: '82513' } };
var sample2 = { 'messages.12': { body: '123\r\n456\r\n789\r\n', db_msg_id: '12'} };
var base_doc = { conv_hash: '711_34401', messages: {} };
//## FAILS ##
collection.update({conv_hash: '711_34401'}, base_doc, {upsert: true }, function() {
collection.update({conv_hash: '711_34401'}, {$set: sample1}, function(){
collection.update({conv_hash: '711_34401'}, base_doc, {upsert: true }, function() {
collection.update({conv_hash: '711_34401'}, {$set: sample2}, function(){
db.close();
});
});
});
});
//### WORKS: ##
// collection.update({conv_hash: '711_34401'}, base_doc, {upsert: true }, function() {
// collection.update({conv_hash: '711_34401'}, {$set: sample1}, function(){
// collection.update({conv_hash: '711_34401'}, {$set: sample2}, function(){
// db.close();
// });
// });
// });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment