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

如何避免服务器每次刷新/重启时触发insertMany()重复插入数据?

解决Mongoose每次服务器重启重复插入数据的问题

核心问题

当前代码在服务器每次启动/刷新时都会直接执行insertMany(),未判断数据是否已存在,导致重复插入。

解决方案

1. 给Schema添加唯一约束

在你的Schema文件(../models/schema.js)中,给唯一标识字段(示例中的id)添加唯一索引,从数据库层面避免重复数据:

const mongoose = require('mongoose');

const exchangeSchema = new mongoose.Schema({
  id: { type: String, unique: true }, // 标记id为唯一字段
  name: String,
  year_established: Number,
  country: String,
  description: String,
  url: String,
  image: String,
  has_trading_incentive: Boolean,
  trust_score: Number,
  trust_score_rank: Number,
  trade_volume_24h_btc: Number,
  trade_volume_24h_btc_normalized: Number
});

module.exports = mongoose.model('exchanges_2_documents', exchangeSchema);

2. 修改插入逻辑:先检查再插入

修改Data.js中的函数,先查询数据库是否已有目标数据,仅当数据不存在时才执行插入:

const exchanges_2_documents = require('../models/schema')

async function feeding_exchange_2_documents(){
    try {
        // 根据唯一id查询是否已有数据
        const existingItem = await exchanges_2_documents.findOne({ id: "saucerswap-v2" });
        
        if (!existingItem) {
            await exchanges_2_documents.insertMany([
                {
                    "id": "saucerswap-v2",
                    "name": "Saucerswap V2",
                    "year_established": null,
                    "country": null,
                    "description": "",
                    "url": "https://www.saucerswap.finance/swap",
                    "image": "https://assets.coingecko.com/markets/images/1363/small/SAUCERSWAPv2_1.png?1706865384",
                    "has_trading_incentive": false,
                    "trust_score": 6,
                    "trust_score_rank": 100,
                    "trade_volume_24h_btc": 410.8171966697791,
                    "trade_volume_24h_btc_normalized": 410.8171966697791
                }
            ]);
            console.log("初始化数据插入成功");
        } else {
            console.log("数据已存在,跳过插入");
        }
    } catch (error) {
        console.log(error.message)
    }
}

module.exports= feeding_exchange_2_documents

3. 批量插入场景优化

如果需要插入多条数据,可结合唯一索引,在insertMany中添加{ ordered: false }参数,遇到重复的唯一字段时自动跳过该条,继续插入其他数据:

await exchanges_2_documents.insertMany(yourDataArray, { ordered: false });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:20:26