• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

158
Views
I'm getting an error while creating api with the data I pulled from the database

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...

about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 3 years ago · Juan Pablo Isaza Report

0

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, ' '));
});
about 3 years ago · Juan Pablo Isaza Report

0

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

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error