【问题标题】:Error when using _id as a property type in a Mongoose Schema在 Mongoose Schema 中使用 _id 作为属性类型时出错
【发布时间】:2020-05-20 11:45:46
【问题描述】:

我现在正在学习 MongoDB 和 mongoose。我在猫鼬中有一个存档和一个用户模式:

存档.js

var mongoose = require('mongoose');
var User = require('../users/user');

var notesSchema = new mongoose.Schema({
    author: User.userId,
    text: String,
    files:[String]
});

var archiveSchema = new mongoose.Schema({
    name: String,
    priority: String,
    deadline: Date,
    status: String,
    assigned_memnbers: [User.userId],
    notes: [notesSchema],
  });

  archiveSchema.virtual('archiveId').get(function() {
    return this._id;
});

module.exports = mongoose.model('Archive', archiveSchema);

user.js:

var mongoose = require('mongoose');

var userSchema = new mongoose.Schema({
    username: String,
    mail: String,
    bio: String,
    password: String
});

userSchema.virtual('userId').get(function() {
    return this._id;
});

module.exports = mongoose.model('User', userSchema);

当我运行我的服务器时,我得到了错误

TypeError: Invalid value for schema path `author`, got value "undefined"

问题来自author: User.userId,但是我不知道如何在两个表之间进行引用。

作为参考,这是我完整的数据库设计或多或少的样子:

欢迎任何有关如何解决此问题或改进整体设计的意见。谢谢你。

【问题讨论】:

    标签: node.js mongodb mongoose nosql schema


    【解决方案1】:

    我认为您所说的是对其他集合的引用:

    author: { type: Schema.Types.ObjectId, ref: 'User' }
    

    assigned_members: [{ type: Schema.Types.ObjectId, ref: 'User' }]
    

    应该可以正常工作。

    来源:Mongoose population

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。我导入了一个模块,只是没有从另一个模块导出。所以我添加了:

      exports.genreSchema = genreSchema;
      

      【讨论】:

        猜你喜欢
        • 2021-09-06
        • 2022-08-08
        • 2018-10-09
        • 2015-06-16
        • 2015-04-24
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        相关资源
        最近更新 更多