Node.js 推送一个新对象不会';t在回调中重新调谐
在将其标记为副本之前: 进一步仔细阅读,我试图从文档本身更新文档。不使用模式或模型。因此,any.findById*会直接跳出窗口 以下是我的模式当前的样子(仅相关部分): 我想在“meta/accessControl/authTokens”中推送一个新对象。我目前的做法是:Node.js 推送一个新对象不会';t在回调中重新调谐,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,在将其标记为副本之前: 进一步仔细阅读,我试图从文档本身更新文档。不使用模式或模型。因此,any.findById*会直接跳出窗口 以下是我的模式当前的样子(仅相关部分): 我想在“meta/accessControl/authTokens”中推送一个新对象。我目前的做法是: UserAccSchema.methods.generateAuthToken = function (authAgent, cb) { console.info("MongoUser | Auth | Attem
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吗
{“n”:1,“nModified”:1,“ok”:1}
要返回修改后的文档,可以使用
比如db.foo.findOneAndUpdate({class:3},{$set:{name:231}},{new:true})
将按以下方式返回响应:
{
"_id" : ObjectId("58db5f4a611f51a2bf08bbb0"),
"name" : "parwat",
"class" : 3
}
.update
返回已修改文档的数量,而不是对象。请查看@pk08这就是我想知道的原因,是否有其他方法来获得更新的部件。@Veeram,我已经检查过了。我希望返回更新的部分(在我的例子中,是我刚刚推到原始文档中的对象),而不是整个文档。给你。。您需要将投影与elemMatch一起使用,以获取更新的嵌入对象。我假设您的任务是这样的
{
"_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);
}
});
};