【问题标题】:Problem to find data from mongodb with node js使用节点 js 从 mongodb 中查找数据的问题
【发布时间】:2019-02-23 22:37:12
【问题描述】:

当我尝试从 mongo b 数据库中获取数据时,我得到了整个对象,例如 _id,title(该对象的所有属性)。但我只需要标题。我该如何解决这个问题?

模型和 mongo 架构

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

const IntroSchema = new Schema ({
 title: {
     type: String,
     required: true
 }
 });

let Intro = module.exports = mongoose.model("Intro", IntroSchema);

这是获取数据的请求

app.js

router.get('/', (req, res) => {
Intro.find({}, (err, title) => {
if (err) {
  res.send("Something went wrong: " + err);
} else {
  res.render('index', {
    title
  })
}
});
});

通过 ejs 视图引擎渲染。

index.ejs

<h1><%= title %></h1>

See full project on github

【问题讨论】:

    标签: node.js database mongodb express ejs


    【解决方案1】:

    您可能对命名响应标题感到困惑。

    试试:

    router.get('/', (req, res) => {
      Intro.find({}, (err, items) => {
        if (err) {
          res.send("Something went wrong: " + err);
        } else {
          res.render('index', {
            title: items[0].title
          })
        }
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 2019-06-29
      相关资源
      最近更新 更多