2016-06-28 3 views
3

以前はmongoコレクションにドキュメントを挿入していたと言えます。ノードのMongoDBでfindOneAndUpdateを使用する方法

MongoClient.connect(url, function(err,db){ 
     if(err) {throw err;} 
     else { 
     document = {action: "alert", 
        protocol: "udp", 
        port: "80", 
        _id: "12" } 
     var collection = db.collection("connections"); 
     collection.insertOne(document, function(err,result){ 
      if (err) {throw err;} 
      else { 
      console.log("Successful") 
      db.close(); 
      } 
     } 
     } 

ここで、プロトコルフィールドを更新します。これまでのところ運がないものは

 MongoClient.connect(url, function(err,db){ 
     if (err) { throw err; } 
     else { 
     var collection = db.collection("connections"); 
     collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {new: true}, function(err,doc) { 
      if (err) { throw err; } 
      else { console.log("Updated"); } 
     }); 
     } 
    }); 

私は間違ったパラメータをfindOneAndUpdateメソッドに渡していますか?私はデータベースに正しく接続します。

+0

実際に_idを「12」と定義していますか?または、あなたはMongoのObjectIdを受け入れていますか?後者の場合、ObjectIdインスタンスではなくクエリ内の_idとして文字列を渡すので、ドキュメントを見つけることができません。また、エラーはどうなっていますか?最後に、なぜ '{new:true}'? –

+0

あなたはMongoose(http://mongoosejs.com/index.html)など何かを使っていますか?普段はnode.jsに人々が使用しているものですエラーメッセージがありますか? – kazu

+0

私はノードにmongodbを使用しています。また、正しく更新されるため_idエラーではなく、ドキュメント全体をプロトコルのみに置き換えます。 – Spothedog1

答えて

0

あなたの3番目の引数は有効ではありません({新しい:真})

6

私は文書が一致しない場合にtrueに設定された「アップサート」は、新しい文書を作成した場合は、

MongoClient.connect(url, function(err,db){ 
    if (err) { throw err; } 
    else { 
    var collection = db.collection("connections"); 
    collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {upsert: true}, function(err,doc) { 
     if (err) { throw err; } 
     else { console.log("Updated"); } 
    }); 
    } 
}); 

を試みるべきだと思いますクエリ基準。

0
MongoClient.connect(url, function(err,db){ 
    if (err) { throw err; } 
    else { 
    var collection = db.collection("connections"); 
    collection.findOneAndUpdate({"_id": "12"}, {$set: {"protocol": "http"}}, function(err,doc) { 
     if (err) { throw err; } 
     else { console.log("Updated"); } 
    }); 
    } 
}); 

ここでレコードを更新するには、{upsert:true}と{new:true}を使用する必要はありません。このソリューションはうまくいきます。一度試してみて、コードにエラーがあれば教えてください。

フィルタに一致するものがなければ、更新文書を挿入し、upsertを使用します。

関連する問題