2015-10-18 43 views
0

我对Mongodb非常陌生,迄今已成功使用Find, Insert, Update方法。然而,随着Delete功能我不能够访问写结果无法从回调中的remove()访问writeresult

插入工程

productCollection.insert(newProduct, function (err, result) { 
     callBack(err, { message: result["insertedCount"] + ' product created successfully.' }); 
    }); 

查找工程

productCollection.find({}).toArray(function (err, docs) { 
     callBack(err, { product: docs }); 
    }); 

删除(有问题)

productCollection.remove({ id: pId }, { justOne: 1 }, function (err, result) { 
     callBack(err, { message: result}); 
}); 

这里的时候,我回到{消息:结果}我得到

{ 
    "message": { 
     "ok": 1, 
     "n": 0 
    } 
} 

但我想其实从结果中读取“N”以示无文件删除

试过以下

  1. {消息:R t esult [ “N”]}
  2. {消息:结果[ “nRemoved”]}

但在这两种情况下,它返回空对象{}。

回答

1

谢谢Yelizaveta指出已弃用的方法。然而,在我的情况下,在工作

productCollection.removeOne({ id: pId }, { w: 1 }, function (err, r) { 
    callBack(err, { message: r.result["n"]}); 
}); 

我无法得到r.result.n而不工作r.result [ “N”]工作,我不明白。

2

按照2.0版本的Node.js的MongoDB驱动程序的API,删除()方法已过时,你可以使用removeOne()方法:

http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove

为了接收文件数已被删除,您需要使用安全模式以确保删除文档。要做到这一点,通过传递{w:1}给removeOne()函数指定写关注点:

productCollection.removeOne({ _id: pId }, { w:1 }, function(err, r) { 
    // number of records removed: r.result.n 
    callBack(err, { message: r }); 
}); 

希望这会有所帮助。

相关问题