skip to Main Content

I want to make a ".json" page with the data I pulled.
ut
Code

app.get("/:user_id", async (req, res) => {
  let items = [];
  await msgData.find({ userId: req.params.user_id }).then((e) => {
    e.map((e) => {
      for (const [key, value] of e.msgChannelsMsgCount.entries()) {
        items.push({ guildId: e.guildId, channel: key, msgCount: value });
      }
    });
  });
  res.write(JSON.parse(items));
});

Mongoose Schema

import { mongoose } from "./../../dist/tools.js";
const { model, Schema } = mongoose;

const schema = new Schema({
  userId: String,
  guildId: String,
  msgCount: Number,
  msgChannelsMsgCount: Map,
});

const msgdatas = model("msgdatas", schema);
export default msgdatas;

Mongo Output

_id:626f1c8e9abf489a1bed71c1
userId:"337800833888681987"
guildId:"959946061915492373"
msgCount:30
msgChannelsMsgCount:Object
959946062095851523:7
970510925205475429:19
965236713314213889:1
__v:0

undefined:1
[object Object],[object Object],[object Object],[object Object] ^

SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at file:///C:/Users/imkys/OneDrive/Masa%C3%BCst%C3%BC/app/server/app.js:14:18
at processTicksAndRejections (node:internal/process/task_queues:96:5)
[nodemon] app crashed – waiting for file changes before starting…

3

Answers


  1. res.write(JSON.parse(items)); to res.write(items); would work just fine.

    Login or Signup to reply.
  2. try:

    app.get("/:user_id", async (req, res) => {
      let items = [];
      await msgData.find({ userId: req.params.user_id }).then((e) => {
        e.map((e) => {
          for (const [key, value] of e.msgChannelsMsgCount.entries()) {
            items.push({ guildId: e.guildId, channel: key, msgCount: value });
          }
        });
      });
      res.write(JSON.stringify(items, null, ' '));
    });
    
    Login or Signup to reply.
  3. Welcome to the Stack Overflow!

    When you use JSON.parse(<input>) It read string input then turns that string into JS object format.

    As an example:

    {
     "body": 5
    }
    //becomes
    {
     body: 5
    }
    

    which makes it possible for you to use the objects’ body as object.body

    To send json data you should use res.json(items) built-in express method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search