了解mongoose findOne()。remove()
如您所知,在mongoose
,我们可以删除所有年龄为30岁的用户:
User.find({age: 30}).remove(callback);
现在,用findOne()
replacefind()
,我认为它应该只删除一个用户:
User.findOne({age: 30}).remove(callback);
哦,不是我所期望的,上面的代码也删除了所有而不是一个
那么,为什么findOne().remove()
全部移除而不是一个? 这是一个错误或function,为什么?
提前致谢!
P / S: 我知道findOneAndRemove()
会为我删除一个用户,但在这个问题中,我想了解findOne()。remove()
我把这个问题报告给了mongoose队,并得到了答复:
https://github.com/LearnBoost/mongoose/issues/1851#issuecomment-31355346
这是来自aheckmann的消息
“findOne只是设置要运行的命令名,remove()把它改回到一个rice命令,但是没有设定限制,我们应该在3.9中改变它,以便findOne设置限制。
find
和findOne
返回mongoose查询对象,其中只包含有关模型和指定查询的信息。 它没有考虑在callback中首先应用的findOne
。 你期望发生的是有像这个User.findOne({age: 30}, null, {limit: 1}).remove()
设置选项User.findOne({age: 30}, null, {limit: 1}).remove()
因为这只会删除一个,你可以争辩说,这是一个错误,但这取决于使用情况。 就像你已经指出的,正确的方法是使用findOneAndRemove()。
我是一种小白,但你不需要把你的删除callback,因为这是一个asynchronousfunction? 尝试像这样:
User.findOne({age: 30}, function(err, user){ user.remove() })