在将其标记为重复项之前: 进一步仔细阅读,我正在尝试从 DOC 本身更新 DOC。不使用架构或模型。因此,任何 .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}
我想知道的是:
- 我哪里错了?
- 我这样做的方式正确吗?还有其他方法$push 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
}
关于node.js - 推送新对象不会在回调中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43426498/