我正在尝试创建一个较小的架构,以便可以在较大的架构中重复使用。.
我的“用户”模式已定义(在另一个文件中)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const noRights = require('../models/Roles').user_noRights;
const UserSchema = new Schema({
// these are required to create a user
name: {type: String, required: true},
email: {type: String, required: true, lowercase: true},
password: {type: String, required: true},
role: {type: String, required: true, default: noRights},
})
module.exports = User = mongoose.model('users', UserSchema)
这有效(但未使用较小的“用户”模式)
const PostSchema = new Schema({
text: {type: String, required: true },
date: {type: Date,default: Date.now},
user: {
type: Schema.Types.ObjectId,
ref: 'users'
}
});
这是我要使用的较小的“用户”模式:
const userData = new Schema({
type: Schema.Types.ObjectId,
ref: 'users'
});
此处使用了较小的“用户”模式,但失败了:
const PostSchema = new Schema({
text: {type: String, required: true },
date: {type: Date,default: Date.now},
user: { type: userData },
});
这是错误
C:\GitHub\node_modules\mongoose\lib\schema.js:717
[0] throw new TypeError('Undefined type `' + name + '` at `' + path +
[0] ^
[0]
[0] TypeError: Undefined type `Users` at `ref`
[0] Did you try nesting Schemas? You can only nest using refs or arrays.
答案 0 :(得分:0)
我使用npm的“ deepPopulate”模块解决了这个问题-非常好!