Use mongoose in an imported html file

How could i use mongoose in an imported script?
In js/main.html

<script src="js/main.js"></script>

And in main.js

const mongoose = require("mongoose");

This gives as output require is not defined.

Sounds like you want the javascript running on the user’s browser to connect to the database. Potentially you could get this to work, but its not a good idea because then the user and password would be publicly exposed.

Its better to put that mongoose code in a server-side script, for example in a node express app. Try create a new app, selecting node express, and you’ll get a server.js script to connect to the database from.

Then the server app connects to the database, and sends data to the page on the client.

1 Like

ah k thanks, can you give me an example how to pass data through?

Hi @RobinSchapendonkGame, there are different ways of serving data to a client. Two often used ways are:

  • javascript on client page requests data from the server, a nice simple example by Glitch staff is https://glitch.com/~low-db

  • client browser requests a page, server renders a html page from a template plus the data and sends to the client. This is more conceptually difficult, an example by Glitch staff is https://glitch.com/~mongodb-sync

There are a heap of variations on the above, using all sorts of tech, I recommend exploring from Glitch’s home page to see what apps are on show.

1 Like