Node.js + MongoDB doesn't upsert, why?
I can't see the changes pushed to the web server, why?
- the server is running
- I can see in the console before the
save
correct JSON:{ "_id" : "abcd", "key1" : "value1" }
This is the body of my POST message:
["Memorise", [["Diagram", {"_id" : "ab3sdscd", "key2" : "value1"}]]]
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var myServer = http.createServer(function(request, response)
{
if (request.method == 'POST') {
var data = '';
request.on('data', function (chunk){
data += chunk;
});
request.on('end',function(){
var obj = JSON.parse(data);
var databaseName = obj['db']
MongoClient.connect("mongodb://localhost:27017/" + databaseName, function(err, db) {
if(!err) {
if (obj.length == 2) {
var recordsToUpsert = obj[1]
for (var i = 0; i < recordsToUpsert.length; i++) {
var recordToUpsertAndCollection = recordsToUpsert[i]
var collectionName = recordToUpsertAndCollection[0];
var recordToUpsert = recordToUpsertAndCollection[1];
var collection = db.collection(collectionName);
//console.log(collection)
console.log(recordToUpsert)
collection.save(recordToUpsert, {w:1}, {
//console.log("record upserted");
});
};
response.writeHead(200)
response.end()
}
}
});
});
}
});
myServer.listen(3000)
+3
source to share
2 answers
This is your payload being analyzed for obj
:
["Memorise", [["Diagram", {"_id" : "ab3sdscd", "key2" : "value1"}]]]
Here's the problem:
var databaseName = obj['db']
See that you are asking for a "key" called "db". It doesn't exist, hence the name of the database undefined
.
Since JavaScript is "building", the connection string is output like this:
"mongodb://localhost:27017/undefined"
This is where all your data will be.
Fix it with a simple change:
var databaseName = obj[0]
0
source to share