Mongoose 4.x "model.update()" 回调已更改

Mongoose 4.x "model.update()" callback changed

在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 影响的行是否安全?

是的,它们是同一回事。根据 4.0 release notes:

#2552: 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 the replicaSet 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.