簡體   English   中英

如何檢查 email 是否已經存在,不包括當前記錄 mongoose

[英]How to check if email already exists excluding the current record mongoose

我為產品創建了更新路線。 有些字段必須是唯一的。

創建產品時,我會這樣檢查

const emailExists = await Foodlancer.findOne({ email: values.email });

if (emailExists) {
  return res.status(400).json({ error: 'Email already used' });
}

但我不確定在更新產品時如何檢查 email 是否已被使用。

如果我使用上面的代碼,它會為我們正在更新的同一個 object 返回 true。

有沒有辦法排除 object? 我看過$ne$nin但不確定在這種情況下如何使用它們。

有什么建議么?

首先,您可以創建一個唯一索引並在數據庫級別執行此操作。 這不會讓您插入或更新系統中存在的 email。

關於您要執行的邏輯檢查,為什么不使用相同的代碼在更新上創建並添加檢查_id是否與$ne不同

(我假設您正在使用文檔_id進行更新,否則您將只使用實際的 email 進行更新?)

const documentToUpdateId = new ObjectId(req.body._id);
const emailExists = await Foodlancer.findOne({ email: req.body.email, _id: {$ne: documentToUpdateId}});

if (emailExists) {
  return res.status(400).json({ error: 'Email already used' });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM