所以我尝试使用 Mongoose 在数据库中插入数据。每次服务器连接/刷新时,
.insertMany()
都会运行,从而在数据库中插入相同数据的多个副本。我尝试使用 MongoDB Playground 插入数据,然后使用 Mongoose 获取和发送数据,它确实解决了上述问题,但我只想使用 Mongoose 来插入数据。
服务器.js
const express = require('express');
const mongoose = require('mongoose');
const exchange_route = require('../routes/exchanges')
const data= require('../models/data')
const app = express();
const port = 3000;
async function connect_to_database() {
try {
await mongoose.connect('mongodb://localhost:27017/REST-2');
console.log("Connected to database");
} catch (error) {
console.error("Failed to connect to database:", error);
}
}
connect_to_database();
data();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.use('/exchanges',exchange_route)
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
数据.js
const exchanges_2_documents = require('../models/schema')
async function feeding_exchange_2_documents(){
try {
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
}
]
)
} catch (error) {
console.log(error.message)
}
}
module.exports= feeding_exchange_2_documents
看起来您正在尝试实现一个称为“数据库播种”的概念,其中将一组初始文档插入到 MongoDB 集合中。 但是,由于您的
server.js
文件在每次应用程序启动时运行,因此您的
run()
函数也将在每次应用程序启动时运行。这意味着您的 feeding_exchange_2_documents()
函数每次都会插入文档。显然你想避免这种情况。播种通常是在首次启动应用程序或移动环境时在命令行上完成,但您可以采取的一种快速而简单的方法是将 run()
调用移动到路由处理程序中,如下所示:
connect_to_database();
//data(); //< Delete it from here
app.get('/', (req, res) => {
res.send('Hello World');
});
app.get('/seed', async (req, res) => {
try{
await data(); //< Add it in here
res.send('Database Seeded');
}catch(err){
res.send('Error when seeding')
}
});
理想情况下,您想要检查要播种到集合中的文档是否已经存在,这样您就不会继续添加它们,因此只需检查
"id": "saucerswap-v2"
并在它已经存在时抛出错误,如下所示:
async function feeding_exchange_2_documents(){
try {
const doc = await exchanges_2_documents.findOne({id: "saucerswap-v2"});
if(!doc){ //< doc not found so free to insert
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
}
]
)
}else{
// Doc was found so throw an error
throw new Error('Database record already exists')
}
} catch (error) {
console.log(error.message);
// Remember to throw the error again so that the route handler knows
throw error;
}
}