I have a problem to insert a API call with request in mongodb with mongoose. I am very new in this topic. Need your help.,. Here ist my test.js. how can i solve this problem any ideas. My target is to save the Api call from the url and then update it all 30 min but at the moment i was very happy when i could save the call. For all help i am very grateful.
When i start with node test.js then i get only the ids in mongodb not more.
const request = require('request');
const path = require('path');
const https = require('https');
const mongoose = require('mongoose');
const port = 3000;
const dbUrl = process.env.xxx || 'mongodb://localhost:27017/testingDB';
mongoose
.connect(dbUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => {
console.log('Connection ready');
})
.catch((err) => {
console.log(err);
});
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
//Create a Schema
const coinSchema = new mongoose.Schema({
id: String,
coin_id: Number,
name: String,
symbol: String,
market_cap_rank: String,
thumb: String,
small: String,
large: String,
slug: String,
price_btc: Number,
score: Number,
});
//Create a Model with collection coins
const Coin = mongoose.model('Coin', coinSchema);
app.get('/testing', async (req, res) => {
const url = 'https://api.coingecko.com/api/v3/search/trending';
request({ url, json: true }, (error, response) => {
if (error) {
console.log(error);
} else {
Coin.insertMany(response.body.coins);
console.log(response.body.coins);
}
});
});
app.listen(port, () => {
console.log(`Server ready on port ${port}`);
});```
Try
request({ url: 'https://api.coingecko.com/api/v3/search/trending', json: true }, function (error, response, body) {
// ...
Coin.insertMany(body.coins.map(({ item }) => item));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.