如何通过集合名称获取猫鼬模型?

时间:2021-02-09 10:03:04

标签: node.js mongoose

集合是 chats。 模型名称为 Chat

import {model, Schema} from 'mongoose';
const ChatSchema = new Schema(
    {
        username: {type: String, required: true, index: true},
        message: {type: String, required: true},
    }
);
export default model('Chat', ChatSchema);

我可以通过 mongoose.model('Chat') 获得模型就好了。

但是,有没有办法通过集合名称获得Chat模型 chats

1 个答案:

答案 0 :(得分:0)

您还需要在架构中设置集合名称:

const ChatSchema = new Schema(
    {
        username: {type: String, required: true, index: true},
        message: {type: String, required: true},
    },
    { collection: 'chats' } // <-- here
);

Reference