You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在两个MongoDB模型间实现设备数据填充下拉列表?

解决设备下拉填充与模型关联问题

1. 渲染表单时加载设备数据到下拉列表

首先修改渲染new.ejs的路由,先查询所有设备数据并传给模板:

// 示例路由文件 routes/debits.js
const Device = require('../models/Device');
const Debit = require('../models/Debit');

// 渲染新建Debit的表单页面
router.get('/new', async (req, res) => {
  try {
    // 查询数据库中所有设备
    const devices = await Device.find({});
    // 将设备数据传入模板
    res.render('debits/new', { devices });
  } catch (err) {
    console.error(err);
    res.status(500).send('加载设备数据失败');
  }
});

然后在new.ejs中遍历设备生成下拉选项(如需多选,给select标签加multiple属性):

<form action="/debits" method="POST">
  <!-- 其他表单字段:比如借出日期 -->
  <div>
    <label for="devices">选择设备:</label>
    <select name="devices" id="devices">
      <% devices.forEach(device => { %>
        <option value="<%= device._id %>"><%= device.deviceDescription %></option>
      <% }) %>
    </select>
  </div>
  <!-- 员工选择字段、提交按钮等 -->
  <button type="submit">创建借出记录</button>
</form>

2. 处理表单提交,建立双向关联

提交表单后,在POST路由中完成Debit创建+关联设备的双向更新:

router.post('/', async (req, res) => {
  try {
    // 处理设备ID:单选时是单个值,多选时是数组,统一转为数组格式
    const deviceIds = Array.isArray(req.body.devices) ? req.body.devices : [req.body.devices];
    
    // 创建Debit记录
    const newDebit = await Debit.create({
      debitDate: req.body.debitDate,
      devices: deviceIds,
      employees: req.body.employees // 员工选择逻辑同设备
    });

    // 更新关联的Device记录,将当前Debit的ID加入设备的debits数组
    await Device.updateMany(
      { _id: { $in: deviceIds } },
      { $push: { debits: newDebit._id } }
    );

    res.redirect('/debits'); // 跳转到借出记录列表页
  } catch (err) {
    console.error(err);
    res.status(400).send('创建借出记录失败');
  }
});

3. 查询Debit时获取关联的Device数据

需要展示借出记录详情时,用populate方法加载关联的设备完整信息:

// 查询单个Debit详情
router.get('/:id', async (req, res) => {
  try {
    const debit = await Debit.findById(req.params.id)
      .populate('devices') // 加载关联的设备数据
      .populate('employees'); // 加载关联的员工数据
    res.render('debits/show', { debit });
  } catch (err) {
    console.error(err);
    res.status(404).send('未找到该借出记录');
  }
});

在模板中即可直接访问设备的详细字段,比如show.ejs:

<h1>借出记录详情</h1>
<p>日期: <%= debit.debitDate %></p>
<h3>关联设备:</h3>
<ul>
  <% debit.devices.forEach(device => { %>
    <li><%= device.deviceDescription %> (库存编号: <%= device.inventoryNumber %>)</li>
  <% }) %>
</ul>

内容的提问来源于stack exchange,提问作者Nane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:27:38