【问题标题】:Mongo find() returns [object Object] in expressMongo find() 在 express 中返回 [object Object]
【发布时间】:2019-07-28 16:33:16
【问题描述】:

所以基本上我正在尝试从 header.ejs 访问 Pages 集合

app.use(function(req,res,next){
    res.locals.pages= Pages.find();
    next();
});

但是当我尝试从 html 访问它时,它会显示 [object object]

当我在 console.log 上显示它时,它显示了很多

createIndexes instead.
Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map {}, _posts: Map {} },
  _executionCount: 0,
  mongooseCollection: 
   NativeCollection {
     collection: Collection { s: [Object] },
     opts: 
      { bufferCommands: true,
        capped: false,
        '$wasForceClosed': undefined },
     name: 'pages',
     collectionName: 'pages',
     conn: ....................

如何通过数组从 html 访问?

【问题讨论】:

    标签: mongodb express mongoose schema mongoose-schema


    【解决方案1】:
    1. Pages.find() 默认会返回一个游标。您需要使用callback 来处理您发现的内容:
    app.use(function(req, res, next) {
      Pages.find({}, (err, pages) => {
        if (err) return next(err);
        res.locales.pages = pages;
        return next();
      });
    });
    
    1. 签出 Converting an object to a string 获取有关如何将对象或数组转换为 string 的信息。默认情况下,当您将对象转换为字符串时,它将读取[object Object](您可以通过const a = {}; console.log({}.toString()) 验证这一点)

    【讨论】:

    • 你每天回答这样一个问题总能得到最高分!
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多