【问题标题】:mongoose population (refs) is not working猫鼬种群(参考)不起作用
【发布时间】:2021-12-31 14:55:07
【问题描述】:

我创建了两个模型,我试图将一个模型引用到另一个模型,但它不起作用,我对此一无所知。我使用它的方式与猫鼬示例中的完全相同,但它没有帮助,我的工作和他们的示例之间的唯一区别是我对两个模型都有两个不同的文件,我将它们导出以在另一个文件中使用

我参考Mongoose的例子

第一个模型

const userModel = require('./userModel')
const {Schema} = mongoose

const tweet = new Schema({
    date: {
        type: Date,
        required: true,
    },
    msg:{
        type: String,
        maxlength:140,
        required:true
    },
    tweetid:{
        type: mongoose.Types.ObjectId
    }
})

const tweetSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'userModel'
    },
    tweets: {
        type: [{tweet}],
        default: []
    }
})

const tweetModel = mongoose.model('tweet',tweetSchema)

module.exports = tweetModel

第二个模型

const {Schema} = mongoose

const userSchema = new Schema({
    email: {
        type:String,
        required: true,
        unique: true,
        trim:true
    },
    password: {
        type:String,
        required: true,
        trim:true
    },
    follows: {
        type: [String],
        default: []
    }
})

const userModel = mongoose.model("User",userSchema) 

module.exports = userModel

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您的参考字符串应该等于您传递给mongoose.model的型号名称:

    const tweetSchema = new Schema({
        user: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        },
        tweets: {
            type: [{tweet}],
            default: []
        }
    })
    

    【讨论】:

    • 我认为架构名称是指模型名称const userModel = mongoose.model("User",userSchema) 所以我应该在参考中使用 userModel 还是 User
    • 我还是不能得到结果,还是一样
    • 您的查询是什么以获得结果?
    • 我正在使用 Robo 3t 查看结果,所以我没有使用任何查询
    • 那你怎么知道它不起作用?
    猜你喜欢
    • 2016-07-02
    • 2016-07-31
    • 2015-10-17
    • 2019-09-13
    • 2017-06-02
    • 1970-01-01
    • 2013-01-25
    • 2015-08-08
    • 2018-02-10
    相关资源
    最近更新 更多