【问题标题】:How can I use a smaller schema, that has a reference, within a larger schema?如何在较大的架构中使用具有引用的较小架构?
【发布时间】:2019-08-24 04:34:47
【问题描述】:

我正在尝试创建一个较小的架构,以便在更大的架构中重复使用..

我的“用户”架构已定义(在另一个文件中)

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.

【问题讨论】:

    标签: node.js mongoose schema


    【解决方案1】:

    我使用 npm 的“deepPopulate”模块解决了这个问题 - 非常好!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-22
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 2020-11-10
      相关资源
      最近更新 更多