[英]How to check if a document exists without retrieving it: Mongoose
I am using Mongoose to connect to MongoDB and perform CRUD operations on it. 我正在使用Mongoose连接到MongoDB并对其执行CRUD操作。 One of my collections has a lot of data in its individual documents (records).
我的一个馆藏在其各个文档(记录)中有很多数据。 At a point in my code, I want to check if a document with particular
id
field exists already in the collection, and if it does, then I can show a proper error to the user. 在我的代码中,我想检查集合中是否已存在具有特定
id
字段的文档,如果存在,则可以向用户显示适当的错误。
Currently, I am using the findOne()
method available in the Mongoose
library. 当前,我正在使用
Mongoose
库中提供的findOne()
方法。 The problem with this method (or any other find
prefixed methods) is that it retrieves the data, which takes a bit time if there is a crazy bunch of data stored. 这种方法(或任何其他使用
find
前缀的方法)的问题在于它检索数据,如果存储了一大堆数据,这将花费一些时间。
I am looking for a way to get some kind of boolean
as a result indicating if the document exists or not, without actually getting the whole document itself. 我正在寻找一种获取某种
boolean
,以指示文档是否存在,而不实际获取整个文档本身。
Alternatively you could use countDocuments() to check the number of documents in the query? 或者,您可以使用countDocuments()来检查查询中的文档数? This will just count the number rather than returning it.
这只会计算数字而不是返回数字。
Pass id in findOne()
在
findOne()
传递ID
Make a one common function. 做一个共同的功能。
const objectID = require('mongodb').ObjectID
getMongoObjectId(id) {
return new objectID(id)
}
Now just call function 现在只需调用函数
findOne({_id:common.getMongoObjectId('ID value hear')})
It will same as where
condition in mysql. 它将与mysql中的
where
条件相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.