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

基于Node.js与MongoDB的同步应用构建需求及步骤

构建网页数据同步到MongoDB的应用实现方案

嘿,我来帮你把这个同步应用的实现步骤梳理清楚,完全按照你要求的顺序来,代码示例都是实战可用的:

  • 01- 连接至MongoDB的'db'数据库
    首先得用MongoDB的客户端驱动建立连接,我这里用Node.js环境下的官方mongodb包来写异步连接逻辑,你可以直接套用:

    const { MongoClient } = require('mongodb');
    const uri = 'mongodb://localhost:27017'; // 记得替换成你的MongoDB服务地址
    const client = new MongoClient(uri);
    
    async function connectToDB() {
      try {
        await client.connect();
        const targetDB = client.db('db');
        console.log("已成功连接到MongoDB的'db'数据库");
        return targetDB;
      } catch (error) {
        console.error("数据库连接失败:", error);
        throw error; // 抛出错误方便上层处理
      }
    }
    
  • 02- 创建名为'cas'的集合
    连上数据库后,直接创建指定集合就行——如果集合已经存在,这个操作不会报错,很省心:

    async function createCasCollection(db) {
      const casCollection = await db.createCollection('cas');
      console.log("已成功创建'cas'集合");
      return casCollection;
    }
    
  • 03- 检查网页是否有更新
    总不能每次都傻乎乎爬整个网页吧?我们用HTTP头里的Last-Modified来判断网页有没有更新,省流量又高效。这里用axios发HEAD请求拿头信息:

    const axios = require('axios');
    
    // 你得自己实现这两个函数,把上次的更新时间存在本地文件或者数据库里
    async function getLastRecordedUpdateTime() {
      // 示例:从本地文件读取上次记录的时间
      // return fs.readFileSync('./last-update-time.txt', 'utf8');
    }
    
    async function saveLatestUpdateTime(time) {
      // 示例:把最新的更新时间存到本地文件
      // fs.writeFileSync('./last-update-time.txt', time);
    }
    
    async function hasPageUpdated(targetUrl) {
      try {
        const headResponse = await axios.head(targetUrl);
        const currentLastModified = headResponse.headers['last-modified'];
        const savedLastModified = await getLastRecordedUpdateTime();
    
        if (!savedLastModified || currentLastModified !== savedLastModified) {
          await saveLatestUpdateTime(currentLastModified);
          return true; // 网页有更新,走后续爬取流程
        }
        return false; // 没更新,直接跳步骤07
      } catch (error) {
        console.error("检查网页更新状态失败:", error);
        return false; // 出错时默认算没更新,避免程序崩掉
      }
    }
    
  • 04- 使用Cheerio进行网页爬取,获取$变量
    确认网页有更新后,就可以爬取内容并用Cheerio解析了,完全符合你要的格式:

    const cheerio = require('cheerio');
    
    async function fetchAndParsePage(targetUrl) {
      const pageResponse = await axios.get(targetUrl);
      const $ = cheerio.load(pageResponse.data); // 就是你要的$ = cheerio.load(body)
      console.log("已成功加载并解析网页内容");
      return $;
    }
    
  • 05- 处理对象,提取所需信息并整理为指定JSON格式
    这一步得根据你目标网页的DOM结构来调整选择器,我给你写个示例,假设数据在表格行里,你照着改就行:

    function extractAndFormatData($) {
      const jsons = [];
      // 这里的选择器要换成你网页实际的元素类名或标签
      $('table tr.data-row').each((index, element) => {
        const year = parseInt($(element).find('td.year').text().trim());
        const country = $(element).find('td.country').text().trim();
        const value = parseInt($(element).find('td.value').text().trim());
    
        // 只添加有效数据,避免空值或NaN
        if (!isNaN(year) && country && !isNaN(value)) {
          jsons.push({ year, country, value });
        }
      });
      console.log("数据提取并整理完成:", jsons);
      return jsons;
    }
    
  • 07- 无更新时的后续处理
    要是网页没更新,就输出个提示,然后把数据库连接关掉就行:

    async function handleNoUpdate() {
      console.log("网页无更新,无需同步数据");
      await client.close();
      console.log("已断开MongoDB连接");
    }
    

最后,把所有步骤串起来的主函数也给你写好了,直接启动就行:

async function runSyncApp(targetUrl) {
  try {
    // 步骤01:连接数据库
    const db = await connectToDB();
    // 步骤02:创建cas集合
    const casCollection = await createCasCollection(db);
    // 步骤03:检查网页更新
    const isUpdated = await hasPageUpdated(targetUrl);
    
    if (isUpdated) {
      // 步骤04:爬取并解析网页
      const $ = await fetchAndParsePage(targetUrl);
      // 步骤05:提取整理数据
      const syncData = await extractAndFormatData($);
      // 可选:把整理好的数据插入cas集合
      await casCollection.insertMany(syncData);
      console.log("数据已成功同步到cas集合");
      await client.close();
    } else {
      // 步骤07:无更新处理
      await handleNoUpdate();
    }
  } catch (error) {
    console.error("同步应用执行出错:", error);
    await client.close();
  }
}

// 替换成你的目标网页URL,启动应用
runSyncApp('https://your-target-webpage.com');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:47:05