在猫鼬中填充使用一种模型而不是另一种模型

时间:2021-05-29 16:42:53

标签: mongodb populate

我的房间模型与线程和用户模型有关系。在通过 GET 将它们带入时,我还想带上 USER 和 THREAD 的相关文件,但它只带了我 USER 并带了我空的 THREAD

模型 - Rooms.js

    const { Schema, model } = require('mongoose');

const RoomSchema = Schema({
    name: {
        type: String, 
        require: true
    },
    room_id: {
        type: String, 
        require: true
    },
    password: {
        type: String,
        require: true
    },
    thematic: {
        type: Schema.Types.ObjectId,
        ref: 'Thematic',
        required: true
    },
    user: [{ type: Schema.Types.ObjectId, ref: 'User', require: true }],
    thread: [{ type: Schema.Types.ObjectId, ref: 'Thread', require: true }]
});

module.exports = model('Room', RoomSchema );

模型 - Thread.js

const { Schema, model } = require('mongoose');

const ThreadSchema = Schema({
    title: {
        type: String, 
        require: true
    },
    bodyThread: {
        type: String, 
        require: true
    },
    room: { type: Schema.Types.ObjectId, ref: 'Room', require: true },
    user: { type: Schema.Types.ObjectId, ref: 'User',required: true }
});

module.exports = model('Thread', ThreadSchema, 'thread' );

控制器动作

const getRooms = async (req, res = response) =>{
    const rooms = await Room.find().populate('thread').populate('user', 'username');

    return res.json({
        ok: true,
        rooms
    });
};

如果在填充中我放了“用户”,它可以正常工作

Mongo DB 指南针

Threads collections

Rooms collections

0 个答案:

没有答案
相关问题