2017-04-15 51 views
1

將其標記爲重複之前: 請仔細閱讀,我試圖從DOC本身更新DOC。不使用SCHEMA或MODEL。因此,任何.findById *都會直接出現在窗口之外。推送一個新對象不會在回調中被重新調用

這裏是我的架構目前看起來像(只有相關部分):

let UserAccSchema = new Schema({ 
meta : { 
accessControl: { 
authTokens:[{ 
    issuedOn: { 
     type: Date, 
     default: Date.now() 
    }, 
    expiresOn: { 
     type: Date, 
     default: Date.now() + 1728000000 //Defaults to 20-days 
    }, 
    lastUsage: { 
     type: Date, 
     default: Date.now() 
    }, 
    authAgent: { 
     type: String, 
     default: "default" 
    } 
}]}} 
}); 

我要推一個新的對象在「元/ AccessControl的/ authTokens」。我目前的做法是:

UserAccSchema.methods.generateAuthToken = function (authAgent, cb) { 
    console.info("MongoUser | Auth | Attempting to generate auth token for user | " + this._id); 
    this.update({ 
     $push: { 
      "meta.accessControl.authTokens": { 
       authAgent: authAgent 
      } 
     } 
    }, {safe: true, new: true, upsert:true}, function (err, obj) { 
     if (err) { 
      console.error("MongoUser | Auth | Error occurred while saving auth-token information | " + err); 
      cb(new AppError("Auth token cannot be generated. Please try again.", AppError.ErrorCode.INTERNAL_SERVER_ERROR)); 
     } else { 
      console.info("MongoUser | Auth | Auth token for user was generated | " + JSON.stringify(obj)); 
      cb(null, obj); 
     } 
    }); 
}; 

上面的代碼做的工作,但我有推新對象時的問題,新的對象不獲取返回:

function(err,obj) { 

} 

而是返回此:

{"n":1,"nModified":1,"ok":1} 

我想知道的:

  • 我在哪裏錯了?
  • 我這樣做是正確的嗎?任何其他方式來$推動obj?

謝謝

+0

'.update'返回修改的文檔的數量,而不是對象 –

+0

請看一看。 http://stackoverflow.com/questions/31808786/mongoose-difference-of-findoneandupdate-and-update – Veeram

+0

@ pk08這就是爲什麼我想知道,是否有任何其他方式來做到這一點,以獲得更新的部分。 – AnkitNeo

回答

1

.update只有返回修改後的一些文件

{"n":1,"nModified":1,"ok":1}

返回修改後的文件可以使用findOneAndUpdate

db.foo.findOneAndUpdate({class: 3}, {$set:{name: 231}}, {new: true}) 將返回響應如

{ 
    "_id" : ObjectId("58db5f4a611f51a2bf08bbb0"), 
    "name" : "parwat", 
    "class" : 3 
} 
0
UserAccSchema.methods.generateAuthToken = function (authAgent, cb) { 
    console.info("MongoUser | Auth | Attempting to generate auth token for user | " + this._id); 
    this.findOneAndUpdate({_id: this._id}, {$set:{ 
      "meta.accessControl.authTokens": { 
       authAgent: authAgent 
      }}, {new: true}, function (err, obj) { 
     if (err) { 
      console.error("MongoUser | Auth | Error occurred while saving auth-token information | " + err); 
      cb(new AppError("Auth token cannot be generated. Please try again.", AppError.ErrorCode.INTERNAL_SERVER_ERROR)); 
     } else { 
      console.info("MongoUser | Auth | Auth token for user was generated | " + JSON.stringify(obj)); 
      cb(null, obj); 
     } 
    }); 
}; 
+0

你爲什麼認爲findOneAndUpdate會在這裏工作? – AnkitNeo

+0

我假設你的任務就是這樣 –

相關問題