简体   繁体   English

如何在不检索的情况下检查文档是否存在:猫鼬

[英]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.

相关问题 如何检查 mongoose 文档中是否存在密钥? - How to check if key exists on mongoose document? 如何使用mongoose检查记录/文档是否已存在于MongoDB? - How to check if a record/document already exists in MongoDB using mongoose? 在保存到Mongoose中之前如何检查数据库中是否存在嵌入式文档 - How to check if an embedded document exists in database before saving in Mongoose 如何在不检索父节点的情况下检查密钥是否存在? [Firebase /数据库] - How to check if a key exists, without retrieving the parent node? [Firebase / Database] 使用 ZCCADCDEDB567ABAE643E15DCF0974E503Z Model 检查文档是否存在于集合中 - Check if document exists in collection with Mongoose Model 如何检查猫鼬中是否存在值 - How to check if a value exists in mongoose 如何查找某个项目是否存在于文档 mongoose 的数组中 - How to find if an item exists in an array of a document mongoose 即使我检查文档是否已存在,Mongoose仍在保存文档 - Mongoose is saving documents even if I check to see if the document already exists 检查文档是否已经存在,如果是,则进行更新,否则创建新的-猫鼬 - Check if document already exists and if yes then update, otherwise create new - Mongoose 如何查看mongoose中是否存在用户? - How to check whether a user exists in mongoose?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM