Mongoose 中 findById({_id:historyId}) 和 findById(historyId) 之间的区别?

问题描述 投票:0回答:1

我正在做我的一个项目,遇到了这个,这让我有点困惑。 我想了解如果两者都会给出相同的输出(如果是的话)为什么?


async getHistory( historyId: string) {
        const { historyId } = query;
        var history = await HistoryModel.findById(historyId);

        //what will happen if i do like this.

        var history = await HistoryModel.findById({_id:hisotryId})
        if (!history) {
            throw new Error(400, ` not found`, ` not found`)
        }
        return history;
    }

node.js typescript express mongoose
1个回答
0
投票

第二次调用

findById
是错误的。 Mongoose 的
findById
采用单个 ID,而不是对象。

第二个电话可能意味着使用

findOne
。 在这种情况下,
HistoryModel.findOne({ _id: historyId })
HistoryModel.findById(historyId)
执行相同的操作,但有下面提到的小警告。

您可以在文档中找到更多信息:

[findById] 通过

_id
字段查找单个文档。
findById(id)
几乎*等同于
findOne({ _id: id })
。如果您想通过文档的
_id
进行查询,请使用
findById()
而不是
findOne()

*
除了它如何对待
undefined
。如果您使用
findOne()
,您会看到
findOne(undefined)
findOne({ _id: undefined })
相当于
findOne({})
并返回任意文档。然而,猫鼬将
findById(undefined)
翻译成
findOne({ _id: null })

https://mongoosejs.com/docs/api/model.html#Model.findById()

© www.soinside.com 2019 - 2024. All rights reserved.