在mongoose 4.x之前,在update()中,您可以检查回调中的第二个参数以查看是否找到了文档.在下面的示例中,您可以使用“rowAffected”查看是否存在包含用户名john的文档.
model.update({ username: "john" }, { ... }, function(err, rowAffected){
if (rowAffected) // document found
但是现在从mongoose 4.x开始,回调中的第二个参数成为MongoDB从更新操作的原始输出.因此,要查找文档是否存在,我必须执行raw.n.
model.update({ username: "john" }, { ... }, function(err, raw){
if (raw.n) // document found
我的问题是“rowAffected”和“raw.n”是一回事吗?如果是这样,当从3.x迁移到4.x时,将raw.n替换为raw.n的所有rowA是否安全?
解决方法:
是的,他们是一回事.根据4.0 release notes:
07001: Upgraded mongodb driver to 2.0.x. Mongoose is a wrapper layer on top of the MongoDB node driver. The mongodb driver recently
released version 2.0, which includes numerous performance and
usability improvements. The new driver, however, introduces a few
changes that affect the way you use Mongoose:
- If you are connecting to
a replica set, you must specify thereplicaSet
option in the
connection string.update
returns a result object from the MongoDB
server, rather than just the number affected. The second parameter to
the callback will now look like{ ok: 1, n: 3 }
rather than simply the
number affected.