如何在另一个模型中引用嵌套模型。例如,有了这个shema,我想在subcategories
架构中引用User
:
var UserSchema = Schema({
publications: [{
name:String,
categories: [{
type: Schema.Types.ObjectId,
refPath: 'Category.subcategories._id'
}]
}]
});
该类别也包含subcategories
,定义如下:
var CategorySchema = Schema({
name: String,
subcategories: [{
name: String
}]
});
我正在尝试引用subcategories
的{{1}}。
答案 0 :(得分:2)
在Category
架构中引用User
可以完成这项工作,因为subcategories
中包含Category
。这就是你需要做的事情:
首先,为包含此代码的Category
模型定义一个shema文件:
const mongoose = require('mongoose');
const CategorySchema = new mongoose.Schema({
name: String,
subcategories: [{
name: String
}]
});
const Category = mongoose.model('Category', 'CategorySchema', 'Category');
module.exports = { Category };
其次,为包含此代码的User
模型定义模式文件:
const mongoose = require('mongoose');
const Category = mongoose.model('Category');
const UserSchema = new mongoose.Schema({
publications: [{
name:String,
Category: Category.schema
}]
});
const User= mongoose.model('User', 'UserSchema', 'User');
module.exports = { User };