如何在另一个模型中引用嵌套模型,mongoose 5.0

时间:2018-05-02 20:01:36

标签: node.js mongoose mongoose-schema mongoose-populate

如何在另一个模型中引用嵌套模型。例如,有了这个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}}。

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 };