2017-04-15 50 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

我假设你的任务就是这样 –

相关问题