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

编程入门 行业动态 更新时间:2024-10-08 01:23:33

<a href=https://www.elefans.com/category/jswz/34/1771452.html style=如何使用 Mongoose、Express 在一页上显示来自 2 个 MongoDB 文档的数据"/>

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

我正在使用 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)我知道我错过了眼前的一些东西。有什么想法可以引导我朝着正确的方向前进吗?

回答如下:

更多推荐

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

本文发布于:2024-05-30 09:39:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   文档   数据   Express   Mongoose

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!