我看不到发送到网络服务器的更改,为什么?
save
之前在控制台中看到正确的JSON:{ "_id" : "abcd", "key1" : "value1" }
这是我的POST消息的正文:
["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)
答案 0 :(得分:0)
这是您的有效负载被解析为obj
:
["Memorise", [["Diagram", {"_id" : "ab3sdscd", "key2" : "value1"}]]]
问题在于:
var databaseName = obj['db']
看到你要求&#34;键&#34;命名&#34; db&#34;。它不存在,因此databaseName为undefined
。
由于JavaScript&#34;字符串化&#34;,因此连接字符串如下所示:
"mongodb://localhost:27017/undefined"
这就是您所有数据的来源。
通过这个简单的更改修复它:
var databaseName = obj[0]
答案 1 :(得分:0)
你为什么不用:
collection.update(criteria,update [[,options],callback]);
for upsert而不是保存?
试试这个:
collection.update({_ id:recordToUpsert._id},recordToUpsert,{upsert:true},yourCallbackMethod);
查看此链接: upsert