mongoose 获取 NodeJS 中的API数据并保存在MongoDB数据库中

j2cgzkjk  于 2022-11-13  发布在  Go
关注(0)|答案(4)|浏览(175)

我是mongooseDB的新手,我试图将数据从这个API插入到数据库中,它创建了集合,但没有创建文档,你知道我做错了什么吗?

import fetch from 'node-fetch';
import mongoose, { mongo } from 'mongoose';

mongoose.connect("mongodb://localhost/highscore");

const postSchema = new mongoose.Schema({

    position: {
        type: Number,
        required: true
    },
    id: {
        type: Number,
        required: true
    },
    score: {
        type: Number,
        required: true
    },

});

const Post = mongoose.model('Players', postSchema);

async function getPlayers() {
    const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
    const response = await getPlayers.json();
    for (let i = 0; i < response.lenght; i++) {

        const post = new Post({
            position: response[i]['position'],
            id: response[i]['id'],
            score: response[i]['score'],

        });
        post.save()

    }
}
getPlayers();```
68de4m5k

68de4m5k1#

MongoDB提供了Api同时插入多个文档的功能,示例如下。

// check if your mongoDb is connected
mongoose.connect(URI).then(err => {
  if(err) console.error({err});
  else console.info("Database Connected");
});

async function getPlayers() {
    const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
   try{
    const response = await getPlayers.json();

    // And then check if you are getting players
    console.log({response});

    const posts = response.map((player) => ({
            position: player['position'],
            id: player['id'],
            score: player['score'],

        }))
   // it's not required to await it, just to be sure it did insert
  await Post.insertMany(posts);
  }catch(error){
    console.log({error})
   }

}
r7xajy2e

r7xajy2e2#

这一行:
对于(令i = 0; i〈响应长度; i++)的情况下,
response.length
现在你的数组是空的,所以保存不会发生

编辑

您确定要导入吗?下面的代码可以工作:

//const fetch = require('fetch'); 
const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/highscore");

const postSchema = new mongoose.Schema({

    position: {
        type: Number,
        required: true
    },
    id: {
        type: Number,
        required: true
    },
    score: {
        type: Number,
        required: true
    },

});

const Post = mongoose.model('Players', postSchema);

async function getPlayers() {
    /*
    const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
    const response = await getPlayers.json();
    for (let i = 0; i < response.lenght; i++) {
*/
        const post = new Post({
            position: '12',
            id: '15',
            score: '300',

        });
        post.save()

    } //} getPlayers();

w8ntj3qf

w8ntj3qf3#

解决方法:

import fetch from 'node-fetch';
import mongoose, { mongo } from 'mongoose';

mongoose.connect("mongodb://127.0.0.1:27017/highscore");

const postSchema = new mongoose.Schema({

    position: {
        type: Number,
        required: true
    },
    id: {
        type: Number,
        required: true
    },
    score: {
        type: Number,
        required: true
    },

});

const Post = mongoose.model('Players', postSchema);

async function getPosts() {
    const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
    const response = await getPlayers.json();
    for( let i = 0;i < response.players.length; i++){

const post = new Post({
    position: response.players[i]['position'],
    id: response.players[i]['id'],
    score: response.players[i]['score'],
});
post.save();

    }

}
getPosts();
rnmwe5a2

rnmwe5a24#

默认情况下,mongodb在localhost上运行:27017
检查您的mongodb连接url

mongoose.connect('mongodb://localhost:27017/highscore')

相关问题