推回一个新的对象不会在callback中被重新调用

在将其标记为副本之前:仔细阅读,我试图从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" } }]}} }); 

我想在“meta / 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?

谢谢

.update只返回修改后的文件数量

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

要返回修改后的文档,可以使用findOneAndUpdate

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

 { "_id" : ObjectId("58db5f4a611f51a2bf08bbb0"), "name" : "parwat", "class" : 3 } 
 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); } }); };