猫鼬模式字段可以引用多个其他模型吗

时间:2020-10-29 05:51:27

标签: javascript node.js mongoose

我有一个名为“ bookmarks”的猫鼬架构字段,我希望它引用多个模型。例如,如果我还有其他两个名为“ 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?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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