2017-01-18 22 views
1

任何人都可以告訴我這是否是合法的貓鼬。我正在嘗試更新學生主文檔數組中的子文檔。當我從shell運行更新查詢時,它可以正常工作,但是從下面的代碼中它不會更新數據。更新查找結果函數裏面的mongo文件

 Student.findOne({ 
    "phone._id": mongoose.Types.ObjectId('587e6409e06170ba1708dc21') 
}, 
{ 
    _id: 0, 
    phone: 1 
}, 
function(err, 
phone){ 
    if(err){ 
     console.log(err) 
    }if(phone.Home==phone.Cell||phone.secondary===undefined){ 
     Student.update({ 
      'Student._id': mongoose.Types.ObjectId('587e6409e06170ba1708dc22'), 
      'phone._id': mongoose.Types.ObjectId('587e6409e06170ba1708dc21') 
     }, 
     { 
      "$set": { 
       'phone.$.number': 453454554 
      } 
     } 
    }) 
}); 

回答

0

按照文檔https://docs.mongodb.com/manual/reference/method/db.collection.update/ db.collection需要幾個參數

db.collection.update(
    <query>, 
    <update>, 
    { 
    upsert: <boolean>, 
    multi: <boolean>, 
    writeConcern: <document>, 
    collation: <document> 
    } 
) 

所以你應該做這樣的事情:

Student.update({ 
    'Student._id' : ObjectId('587e6409e06170ba1708dc22'), 
    <Your Query>, 
    true, 
    true 
}) 
+0

嗨argoden,我的問題是,我是否可以在findOne({「phone._id」:mongoose.Types.ObjectId('587e6409e06170ba1708dc21')},{_ id:0,phone:1},函數(err ,電話){/ /更新邏輯}),我也試着解決findOne的承諾,也沒有幫助。 –

+0

我不認爲你可以。你可以使用findOne在更新查詢中返回的內容,但我認爲你不能在裏面使用它。 – argoden

0

根據您的要求,你可以這樣做:

db.collection.findOneAndUpdate(
    <filter>, 
    <update>, 
    { 
    projection: <document>, 
    sort: <document>, 
    maxTimeMS: <number>, 
    upsert: <boolean>, 
    returnNewDocument: <boolean> 
    } 
) 
+0

請看看我編輯的問題,我已經添加'如果'的條件,我怎麼能實現這一點,使用findOneAndUpdate,因爲我已經在同一個文檔中比較兩個不同的字段。任何建議或幫助非常感謝。 –