【问题标题】:can a mongoose schema field reference more than one other modelsmongoose 模式字段是否可以引用多个其他模型
【发布时间】:2020-10-29 14:13:37
【问题描述】:

我有一个名为“书签”的猫鼬模式字段,我希望它引用多个模型。例如,如果我有 2 个名为“post”和“complain”的其他模型。我希望用户能够为他们添加书签。

const userSchema = new mongoose.Schema({
    fullname: {
        type: String, 
        required: true,
        trim: true,
        lowercase: true
    },
    username: {
        type: String,
        unique: true,
        required: true,
        trim: true,
        lowercase: true
    },
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true,
        lowercase: true,
        validate(value) {
            if (!validator.isEmail(value)) {
                throw new Error('Email is invalid')
            }
        }
    },
    bookmarks: [{
        type: mongoose.Schema.Types.ObjectId,
        required: false,
        ref: 'Post'
    }],
})

下面是一个帖子模型,用户可以在其中发布一般内容

const postSchema = new mongoose.Schema({
    body: {
        type: String, 
        required: true,
        trim: true,
        lowercase: true
    }
})

下面是一个投诉模型,用户可以在其中发布投诉

const complainSchema = new mongoose.Schema({
    body: {
        type: String, 
        required: true,
        trim: true,
        lowercase: true
    }
})

如何获取用户模型中的书签字段,以便能够同时获取投诉模型和帖子模型的对象 ID?

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    您可以将这两个模型嵌套在 userSchema 本身中,就像使用书签 schema 一样。 您也可以参考此链接,希望它能解决您的问题。 链接-:What is the proper pattern for nested schemas in Mongoose/MongoDB?

    【讨论】:

      【解决方案2】:

      这是实现这一目标的正确方法。

      1. 先删除书签

      2. 添加这个

        ref: {  
            kind: String, // <-- Model Name post,complain
            item: {
            type: mongoose.Schema.Types.ObjectId,
            refPath: 'ref.kind',
            fields: String,
            },
        },
        
      3. 当你想获取记录时,你可以使用填充

        model.User.find({})
        .populate({ path: 'ref.item' })
        .then(data=>{console.log(data)})
        .catch(err => {console.log(err)});
        

      【讨论】:

        猜你喜欢
        • 2021-04-19
        • 2019-05-23
        • 2018-07-15
        • 1970-01-01
        • 2013-10-07
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 2021-09-05
        相关资源
        最近更新 更多