Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

359
Views
SvelteKit: ¿Cómo llamar a mongodb sin usar puntos finales?

Quiero llamar a mi base de datos, pero no quiero que los usuarios finales puedan acceder a ella yendo al punto final de la API que configuré. Me preguntaba cómo podría simplemente llamar a mi base de datos desde un archivo en la carpeta lib y simplemente devolver los datos allí. Cuando lo pruebo me sale el error global not defined :

lib/db.js:

 import dotenv from "dotenv"; dotenv.config(); import { MongoClient } from "mongodb"; const uri = process.env["MONGODB_URI"]; const options = { useUnifiedTopology: true, useNewUrlParser: true, }; let client; let clientPromise; if (!uri) { throw new Error("Please add your Mongo URI to .env.local"); } if (process.env["NODE_ENV"] === "development") { if (!global._mongoClientPromise) { client = new MongoClient(uri, options); global._mongoClientPromise = client.connect(); } clientPromise = global._mongoClientPromise; } else { client = new MongoClient(uri, options); clientPromise = client.connect(); } export default clientPromise;

rutas/elementos/index.js:

 import clientPromise from "$lib/db"; export async function get() { const client = await clientPromise; const db = client.db(); const data = await db.collection("items").find({}).toArray(); const items = data.map(({ name }) => ({ name })); if (items) { return { body: { items, }, }; } }

Mi intento: lib/stores/items.js

 import clientPromise from "$lib/db"; import { writable } from "svelte/store"; export const items= writable([]); const fetchItems = async () => { const client = await clientPromise; const db = client.db(); const data = await db.collection("items").find({}).toArray(); const items = data.map(({ name }) => ({ name })); substances.set(items); }; fetchItems();

Probar el código anterior en varios lugares siempre arroja un error global not defined en el cliente.

Encontré una pregunta de alguien con el mismo problema, pero no pude averiguar cómo crear un archivo auxiliar.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

La protección de la API se realiza en el lado del back-end. Por lo general, es un servidor (como NodeJS) o herramientas Nginx/Apache (proxy, etc.). Básicamente, está buscando el tema Política de seguridad de contenido, que es vaporoso pero no está relacionado con SvelteKit.

Por cierto, llamar a DB directamente desde el front-end no sería seguro y no es posible.

over 4 years ago · Santiago Trujillo Report

0

Para obtener datos de cualquier base de datos, debe crear enpoint

Para la autenticación de usuario, puede crear un handle de control:

 export async function handle({ request, resolve }) { let user = await authenticate(request) request.locals.user = user request.locals.isAuthenticated = !!user if (request.path.startsWith('/api')) { if (!user) { return { status: 401, body: JSON.stringify({ error: { message: 'Unauthorized' } }) } } const response = await resolve(request) return response }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!