gpt4 book ai didi

node.js - Mongoose 获取引用模型的_id,无论是否填充

转载 作者:太空宇宙 更新时间:2023-11-03 22:18:10 24 4
gpt4 key购买 nike

鉴于此Category架构

{
title: String,
parent: {
type: Schema.Types.ObjectId,
ref: 'Category',
required: true
}
}

现在如果我有 Category 的实例怎么办? ,但我不知道是否parent是否已填充,我需要 _id (实际上只是十六进制表示)parent .

有更好的方法吗:?

var parentID = (category.parent._id || category.parent).toString();

最佳答案

我认为没有更好的方法了。不过我确实把它放在了虚拟环境中。

schema.virtual('parentID').get(function() {
return this.parent._id || this.parent;
})

如果需要多个方案,这可以很容易地成为一个插件。

关于node.js - Mongoose 获取引用模型的_id,无论是否填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16250164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com