You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从JS文件调用MongoDB服务端函数?已附解决方案

前端点击按钮后调用服务端函数的实现方案

核心逻辑是通过HTTP请求调用服务端端点,再由端点触发对应服务端函数。具体实现步骤及代码如下:

前置准备

  • 安装Node.js环境
  • 执行命令安装依赖:
    npm install express
    npm install nodemon
    
  • 配置MongoDB连接字符串,确保服务端能正常连接数据库(可在VS Code中配置)
  • 根据实际业务数据集,调整MongoDB的Schema定义

服务端代码(Node.js + Express + Mongoose)

import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import 'dotenv/config';

const app = express();

mongoose.set('strictQuery', false);

mongoose.connect(
  process.env.MONGODB_CONNECT_STRING,
  { useNewUrlParser: true }
);

const db = mongoose.connection;

db.once('open', () => {
  console.log('Successfully connected to MongoDB using Mongoose!');
});

app.use(express.json()); // 解析JSON请求体

app.use(cors());

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

// 定义Schema
const documentSchema = new mongoose.Schema({
  id: String,
  title: String,
  artist: String,
  genre: String,
  popularity: Number,
  date: Date,
});

// 创建数据模型
const Document = mongoose.model('Songs', documentSchema);

// 创建歌曲的接口端点
app.post('/create-song', async (req, res) => {
  const { title, artist, genre, popularity, date } = req.body;    // 获取请求参数
  try {
    await createSong(title, artist, genre, popularity, date);   // 调用写入数据库的函数
    res.status(200).send('Song created successfully');
  } catch (error) {
    console.log('Error uploading document:', error);
    res.status(500).send('Internal server error');
  }
});

// 定义异步函数:写入歌曲数据到MongoDB
async function createSong(title, artist, genre, popularity, dateString) {
  try {
    const date = new Date(dateString);
    // 创建数据实例
    const document = new Document({ title, artist, genre, popularity, date });
    // 保存到数据库
    await document.save();
  } catch (error) {
    throw error;
  } finally {
    // 关闭数据库连接
    mongoose.connection.close();
  }
}

前端调用代码(浏览器端JavaScript)

window.onload = function() {
    var title = document.getElementById('title');
    var artist = document.getElementById('artist');
    var genre = document.getElementById('genre');
    var rating = document.getElementById('rating');
    var released = document.getElementById('released');

    // 绑定按钮点击事件触发上传
    document.getElementById('upload-btn').addEventListener('click', uploadSong);

    function uploadSong() {
      const songData = {
        title: title.value,
        artist: artist.value,
        genre: genre.value,
        popularity: rating.value,
        date: released.value
      };
      
      fetch('http://localhost:3000/create-song', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(songData)
      })
        .then(response => {
          if (response.ok) {
            console.log('Song created successfully');
          } else {
            alert('Error:', response.statusText);
          }
        })
        .catch(error => {
          alert('Error:', error.message);
        });
    }
}

注:原前端代码在页面加载时直接执行上传逻辑,实际场景中建议绑定到按钮的click事件触发,上述代码已做对应调整。

内容的提问来源于stack exchange,提问作者Ahmed Zaidan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 03:04:58