[英]findOneAndUpdate works part of the time. MEAN stack
I'm working with the mean stack I'm trying to update the following object: 我正在使用均值堆栈,正在尝试更新以下对象:
{
_id : "the id",
fields to be updated....
}
This is the function that does the updating: 这是执行更新的功能:
function updateById(_id, update, opts){
var deferred = Q.defer();
var validId = new RegExp("^[0-9a-fA-F]{24}$");
if(!validId.test(_id)){
deferred.reject({error: 'invalid id'});
} else {
collection.findOneAndUpdate({"_id": new ObjectID(_id)}, update, opts)
.then(function(result){
deferred.resolve(result);
},
function(err){
deferred.reject(err);
});
}
return deferred.promise;
}
This works with some of my objects, but doesn't work with others. 这适用于我的某些对象,但不适用于其他对象。 This is what is returned when it fails to update:
这是更新失败时返回的内容:
{
ok: 1,
value:null
}
When the function is successful in updating the object it returns this: 当函数成功更新对象时,它将返回以下内容:
{
lastErrorObject: {}
ok: 1
value: {}
}
It seems like Mongo is unable to find the objects I'm trying to update when it fails. 看起来Mongo失败时找不到我要更新的对象。 However, I can locate those objects within the Mongo shell using their _id.
但是,我可以使用它们的_id在Mongo Shell中找到这些对象。
Does anybody know why the driver would be behaving this way? 有人知道为什么驾驶员会这样吗? Could my data have become corrupt?
我的数据可能已损坏吗?
Cheers! 干杯!
I found the answer and now this question seems more ambiguous so I apologize if it was confusing. 我找到了答案,现在这个问题似乎更加模棱两可,如果造成混淆,我深表歉意。
The reason I was able to find some of the documents using ObjectID(_id)
was because I had manually generated some _id
fields using strings. 之所以能够使用
ObjectID(_id)
查找某些文档,是因为我已经使用字符串手动生成了一些_id
字段。
Now I feel like an idiot but, instead of deleting this question I decided to post the answer just in case someone is running into a similar issue. 现在我感觉像个白痴,但我没有删除此问题,而是决定发布答案,以防万一有人遇到类似问题。 If you save an
_id
as a string querying the collection with the _id
field changes. 如果将
_id
另存为字符串,则查询带有_id
字段的集合会更改。
querying collection with MongoDB generated _id
s: 使用MongoDB生成的
_id
查询集合:
collection.findOneAndUpdate({"_id": new ObjectID(_id)}, update, opts)
querying collection with manually generated _id
s: 使用手动生成的
_id
来查询集合:
collection.findOneAndUpdate({"_id": _id}, update, opts)
In the second example _id
is a string. 在第二个示例中,
_id
是字符串。
Hope this helps someone! 希望这对某人有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.