如何使用 mongoose 填充到 mongodb 中的特定字段

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

在这里,我有一个聊天模式,其中有一组消息,其中的项目是包含对用户模式的引用的对象。

const ChatSchema = new mongoose.Schema({
    users: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'user'
        }
    ],
    messages: [
        {
            sender: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'user'
            },
            text: {
                type: String,
                trim: true
            }
        }
    ]
},
    {
        timestamps: true
    }
)

module.exports = Chat = mongoose.model('chat', ChatSchema)

这是用户模式

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    }
},
    {
        timestamps: true
    }
)

module.exports = User = mongoose.model('user', UserSchema)

如何在

sender
数组中的
messages
对象中填充用户模式。我不想在文档的顶层填充。

mongodb mongoose populate
1个回答
0
投票

您可以使用跨多个级别填充又名深度填充。

例如

import User from './models/user';
import Chat from './models/chat';
import mongoose from 'mongoose';
import { config } from '../../src/config';

async function main() {
  mongoose.connect(config.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true });
  const db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  db.once('open', async () => {
    try {
      // seed
      console.log('seeding')
      const users = await User.create([
        new User({ name: 'a', email: '[email protected]', password: '123456' }),
        new User({ name: 'b', email: '[email protected]', password: '123456' })
      ])
      const chat = new Chat({
        users, messages: [{ text: 'message a', sender: users[0] }, { text: 'message b', sender: users[0] }]
      });
      await chat.save();
      
      // test populate
      const chatDoc = await Chat.findOne().populate({
        path: 'messages',
        populate: {
          path: 'sender'
        }
      }).exec();

      // or
      // const chatDoc = await Chat.findOne().populate({ path: 'messages.sender'}).exec();

      // or more shorter
      // const chatDoc = await Chat.findOne().populate('messages.sender').exec();
      console.log('chatDoc.messages[0].sender.name: ', chatDoc.messages[0].sender.name)

    } catch (error) {
      console.log(error);
    } finally {
      await Promise.all([
        db.dropCollection('users'),
        db.dropCollection('chats'),
      ])
      db.close();
    }
  })
}

main();

执行结果:

chatDoc:  {
  users: [ 6462077ea396f30b35d0f37f, 6462077ea396f30b35d0f380 ],
  _id: 6462077ea396f30b35d0f381,
  messages: [
    {
      _id: 6462077ea396f30b35d0f382,
      text: 'message a',
      sender: [Object]
    },
    {
      _id: 6462077ea396f30b35d0f383,
      text: 'message b',
      sender: [Object]
    }
  ],
  createdAt: 2023-05-15T10:20:46.795Z,
  updatedAt: 2023-05-15T10:20:46.795Z,
  __v: 0
}
chatDoc.messages[0].sender.name:  a
© www.soinside.com 2019 - 2024. All rights reserved.