将HTTP请求存储在mongodb上“检测到循环依赖性”

时间:2019-05-09 02:34:06

标签: node.js mongodb express mongoose xmlhttprequest

你好社区!今天下午,我试图将从api接收的数据存储在mongodb中。在此测试中,我使用了“ 请求包”,但我也尝试使用XMLHttpRequest进行了同样的操作。我知道问题出在依赖项引用中:(A-> B-> A),但我无法解决。如果有人告诉我要看哪里,我将不胜感激!

注意:我正在尝试使用节点http模块,但是在使用多个API进行存储时遇到了问题

致谢!

•user.controller.js

const express = require('express');
const router = express.Router();
const userService = require('./user.service');

router.post('/test', test);

module.exports = router;

function test(req, res, next) {
    userService.store(req.body)
        .then(() => res.json({}))
        .catch(err => next(err));
}

•user.service.js

const config = require('config.json');
const db = require('_helpers/db');
const request = require('request');
const User = db.User;

module.exports = {
    store
};

async function store(userParam) {

    let api = request('https://swapi.co/api/people/1/', (error, response, body) => {
        console.log('error:', error);
        console.log('statusCode:', response && response.statusCode);
        return(body);
    });

    const user = new User({
        name: userParam.name,
        swapi: api
    });

    await user.save();
}

•user.model.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
    name: { type: String, required: true },
    swapi: { type: Object, required: true },
    createdDate: { type: Date, default: Date.now }
});

schema.set('toJSON', { virtuals: true });

module.exports = mongoose.model('User', schema);

•db.js 数据库助手

const config = require('config.json');
const mongoose = require('mongoose');
mongoose.connect(config.connectionString, {useNewUrlParser: true });
mongoose.Promise = global.Promise;

module.exports = {
    User: require('../user/user.model')
};

1 个答案:

答案 0 :(得分:0)

我用axios解决了这个问题。

const config = require('config.json');
const db = require('_helpers/db');
const axios = require('axios');
const User = db.User;

module.exports = {
    store
};

async function store(userParam) {

    await axios.get('https://swapi.co/api/people/1/')
        .then(function (response) {
            const user = new User({
                name: userParam.name,
                swapi: response.data
            });
        })
        .catch(function (error) {
            console.log(error);
        });

        user.save();
    }

}

致谢!