我有一個名為 MongoDB 的集合categories,它有一個 self-reference( parent),如下所示。
const schema = mongoose.Schema({
name: String,
parent: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
}
});
export default mongoose.model('Category', schema);
When i query it just returns the object id of the referenced document.
{ "_id": "63731fe1ce1bf2f534f9307e", "name": "玻璃清潔劑", "parent": "63731fbbce1bf2f534f9307d", }
I want to load the document referenced by `parent`, so i used following code to load the parent seperatly.
讓 parentCat = await Category.findOne({ _id: category.parent });
Is there an easy way of doing this because above is bit difficult to maintain if in my opinion.
Thanks
uj5u.com熱心網友回復:
您可以在 mongoose 中使用查詢人口而不是再次查詢父級。
https://mongoosejs.com/docs/populate.html
populate()當您查詢哪個將加載父檔案時,您必須呼叫。
Category.find().populate('parent');
強烈建議您閱讀 mongoose 檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534203.html
