mongodb Mongoose返回的是模式不存在,而实际上它确实存在

2j4z5cfb  于 11个月前  发布在  Go
关注(0)|答案(3)|浏览(152)

我尝试用node js和MongoDB创建一个多租户数据库,它工作得很好,我可以用一个标签创建一个新的数据库,例如:主数据库存储,租户:store_fool,每个租户都有自己的表(集合)。
所以,有什么问题?
我有这个模型:

const BoardSchema = new Schema<Board, Model<Board>>({
    name: {
        type: String,
        required: true
    },
    cards: [{
        type: SchemaTypes.ObjectId,
        ref: 'cards'
    }],
    color: {
        type: String,
        default: '#55AC79'
    }
})

const BoardModel = async (id: string) => {
    try {
        const db = await getTenantDb(id);
        return db!.model('boards', BoardSchema);
    } catch (error) {
        console.log(error);
        throw error;
    }
}

字符串
这是我的卡片模型:

const CardSchema = new Schema<Card, Model<Card>>({
    name: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }
})

const CardModel = async (id: string) => {
    try {
        const db = await getTenantDb(id);
        return db!.model('cards', CardSchema)
    } catch (error) {
        console.log(error);
        throw error;
    }
}


我试着在这些线路板上获取信息:

const Board = await BoardModel(x_tenant as string);
const data = await Board.find();


它工作得很好,如果我在MongoDB Compass GUI上显示集合,它会向我发送正确的集合。
问题是当我试图填充cards时,

const Board = await BoardModel(x_tenant as string);
const data = await Board.find().populate('cards'); //it causes error


我得到以下错误:

MissingSchemaError: Schema hasn't been registered for model "cards".


但是在MongoDB Compass GUI中,集合存在,如果我不填充 prop ,它就可以工作。


的数据
注意boards集合中的卡的id存在于cards集合中

kpbwa7wx

kpbwa7wx1#

我不太熟悉你创建模型的一些语法,但是当mongoose在你指定的字段上进行填充时找不到要使用的特定模型时,它会抛出MissingSchemaError: Schema hasn't been registered for model "cards".。然而,实现这些更改应该可以解决你的问题。
引用cards数组的正确格式为:

cards: [{
   type: SchemaTypes.ObjectId,
   ref: 'Card' //< Change to this
}],

字符串
当您创建模型时,请使用单个标题大小写版本的集合名称。因此:

return db!.model('Board', BoardSchema); //< Change to this
return db!.model('Card', CardSchema) //< Change to this

的数据
有了这些更改,通常情况下,根据您的项目,您需要像这样显式传递模型名称:

const data = await Board.find().populate({path: 'cards', model: Card});


参见mongoose populatePopulate with TypeScript以获得进一步的阅读。

e4eetjau

e4eetjau2#

我认为您必须在populate语句卡中使用单个名称,因为默认情况下,mongo为模型使用单个名称,为表使用复数名称

5anewei6

5anewei63#

const data = await Board.find().populate({path: 'cards', model: Card});

字符串
工作和解决问题!
谢谢

相关问题