2016-04-27 11 views
1

私は役員スキーマを持っていますが、ユーザーが予定を修正したい場合は、DBに入力します。スキーマは次のとおりです。コレクションにデータを挿入できません

officerSchema = mongoose.Schema({ 
    email : {type: String, 
     index: { unique: true } 
    }, 
    appointmentList : Array // array of jsonObject of dates and userID 
}); 

AppointmentListは、任命が行われ、日付とユーザーID(予定を修正したいユーザ)であることを持っていると役員のIDが含まれているJSONオブジェクトの配列です。

しかし、予定のエントリが重複しないように、私はインターネット上で言及されたいくつかの方法を使用しています。今のところ私のために働いた人はいません。私は以下のコードを投稿しています。以下のコードの問題は、決して、すべてのデータを予定リストに挿入しないことです。しかし、update()の代わりにsave()を挿入しても重複も挿入されます。

ここではあなたのために働くかもしれない$addToSet演算子を使用して、私はDBからの配列に追加したいJSONオブジェクト、

{ 
    "id": "1321231231", 
    "appointment": { 
     "userID": "31321", 
     "date": "24 March" 
    } 
} 

var ID = requestObject.id; 
var newObject = {$addToSet: requestObject.appointment}; 
OfficerModel.findOne({_id : ID}, function(err, foundData) { 
    if(err) { 
     console.log(err); 
     return; 
    } 
    else { 
      var dbList = foundData.list; 
      dbList.push(newObject); 
      foundData.update(function(err, updatedData) { 
       if(err) { 
        console.log(err); 
       } 
       else { 
        console.log("successful"); 
       } 
      }); 
    } 
}); 

答えて

0

です。

var appt = { 
    id: "1321231231", 
    appointment: { 
    userID: "31321", 
    date: "24 March" 
    } 
} 

Officer.update(
    {_id: ID}, 
    {$addToSet: {appointmentList: appt}}, 
    function(err) { ... } 
); 

しかし、それは完璧なソリューションではないため、{1:1、2:2}と{2:2、1:1}に等しいと解釈されていないので、彼らは両方の配列に加え得ることができ$ addToSet。完全に重複を避けるために

は、あなたがこのような何かを行うことができます:

var appt = { 
    id: "1321231231", 
    appointment: { 
    userID: "31321", 
    date: "24 March" 
    } 
}; 

Officer.findOne(
    {_id: ID, 'appointmentList.id': appt.id}, 
    function(err, officerDoc) { 
    if (err) { ... } 

    // since no document matched your query, add the appointment 
    if (!officerDoc) { 
     Officer.update(
     {_id: ID}, 
     {$push: {appointmentList: appt}}, 
     function(err) { ... } 
    ); 
    } 

    // since that appointment already exists, update it 
    else { 
     Officer.update(
     {_id: ID, 'appointmentList.id': appt.id}, 
     {$set: {'appointmentList.$.appointment': appt.appointment}}, 
     function(err) { ... } 
    ); 
    } 
    } 
); 

それ以上の操作は、既存の予定がpositional operator使用しています更新します。

+0

いくつかの質問: 'appointmentList.id'は、mongooseにlookmentという名前のテーブル/コレクションフィールドを、appointmentListという名前で伝えてから、appointmentListフィールドのすべてのJsonObjectsをトラバースして、指定されたIDと一致させることができます。もし私たちがappointmentList = [{a:1、[{b:7}]}、...]を持っていれば、これは "b"をappointmentList.a.bでチェックできますか?どうすればbにアクセスできますか?これについて教えるチュートリアルはありますか? – user2498079

関連する問題