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

问题描述 投票:0回答:1

我正在尝试使用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 中,集合存在,如果我不填充该属性,它就可以工作。

注意

id
集合中的卡片
boards
存在于
cards
集合

node.js typescript mongodb mongoose mongoose-populate
1个回答
0
投票

我认为你必须在填充声明卡中使用单个名称,因为默认情况下 mongo 使用模型的单个名称和表的复数名称

© www.soinside.com 2019 - 2024. All rights reserved.