如何使用 Mongoose、Express 在一页上显示来自 2 个 MongoDB 文档的数据

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

我正在使用 NodeJS、Express、EJS 和 Mongoose。我对猫鼬有点陌生,我不确定如何进行。

我定义了两个模型,一个文档通过 ObjectId 链接到另一个。

他们看起来像这样:

`const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const timerSchema = new Schema({
    customer: {
      type: mongoose.Schema.Types.ObjectId, ref: 'Customer',
      required: true
    },
    detailed: {
      type: String,
      required: true
    },
    summary: {
      type: String,
      required: true
    },
 
 }, { timestamps: true }

);


const custDataSchema = new Schema({
    firstName: {
      type: String,
      required: true
    },

    email: {
      type: String,
      required: true
    }, 

 }, { timestamps: true }
);
const Customer = mongoose.model('Customer', custDataSchema);
const Timer = mongoose.model('Timer', timerSchema);

module.exports = Timer;
module.exports = Customer;`

我通过网页输入了所有数据,并正确更新到数据库。

我能够从客户模式中获取一些信息以填充以下路线:

`router.get('/customers/:id', (req, res) => {
    const id = req.params.id;
    Customer.findById(id)
    .then(result => {
        res.render('details', { customer: result, title: 'Customer Details' });
    })
    .catch(err => {
        console.log(err);
    });

})`

但是,我无法弄清楚如何从计时器模型中获取数据以显示在同一页面上。 这是 html/ejs:

  `<div class="container">
            <div class="">
                <h2><%= customer.firstName %></h2>
            </div>
            <div>Email: <%= customer.email %></div>
            <div>Company: <%= tester.summary %> </div>
    </div>`

我的目标是尽可能多地使用 Vanilla JS(绝对不使用 JQuery)我知道我错过了眼前的一些东西。有什么想法可以引导我朝着正确的方向前进吗?

javascript node.js express mongoose ejs
© www.soinside.com 2019 - 2024. All rights reserved.