Паспорт. js Стратегия Spotify - User.Save () не является функцией - PullRequest
1 голос
/ 05 апреля 2020

Я пытаюсь сохранить доступ, а также обновить маркеры sh в моей базе данных, чтобы затем выполнить вызовы API для этого пользователя. Я следовал этим примерам в Интернете как можно лучше как для Passport- js -spotify, для примера JMPerez Passport Spotify, так и для документации Spotify API, но я все еще получаю сообщение об ошибке, говоря, что User.save () не является функцией. Я могу получить информацию о пользователе из БД, если я только найду одно. Кроме того, у меня есть ощущение, что я неправильно настраиваю свой обратный вызов. Немного обернулся со всем этим. Я был бы очень признателен за любую помощь в решении. Я включил свой код ниже. Пожалуйста, дайте мне знать, если вам нужна дополнительная информация.

const express = require("express");
const router = express.Router();
const SpotifyStrategy = require("passport-spotify").Strategy;
const passport = require("passport");
const SpotifyUser = require("../Models/UserSpotify");

var spotifyID;

passport.use(
    new SpotifyStrategy({
        clientID: "84f1c0xxxx29b95xxx0b0fdxxx42f5ce",
        clientSecret: "0b0xxx5944ad8bxx07ab4xxxx",
        callbackURL: "http://localhost:3001/spotify/callback",
    }, function (accessToken, refreshToken, expires_in, profile, done) {

        spotifyID = profile.id
        displayName = profile.displayName
        email = profile._json.email
        profileURL = profile.profileUrl
        accessToken = accessToken
        refreshToken = refreshToken
        country = profile.country
        accountType = profile.product

        console.log(spotifyID)

        process.nextTick(function () {
            SpotifyUser.findOne({
                'spotifyID': spotifyID
            }).then((currentUser) => {
                if (!currentUser) {
                    const User = new SpotifyUser == ({
                        spotifyID: spotifyID,
                        displayName: displayName,
                        email: email,
                        profileURL: profileURL,
                        accessToken: accessToken,
                        refreshToken: refreshToken,
                        country: country,
                        accountType: accountType
                    })
                    User.save(function (err) {
                        if (err) console.log(err);
                        return done(err, user);
                    })
                } else {
                    console.log(currentUser);
                }
            })

        })


router.get(
    "/login",
    passport.authenticate(
        "spotify", {
            scope: ["user-read-email", "user-read-private"],
            showDialog: true,
        }
    ),
    function (req, res) {
        console.log(res.accessToken)
        console.log(res.refreshToken)
    }
);

router.get(
    "/callback",
    passport.authenticate("spotify", {
        failureRedirect: "/login"
    }),
    function (req, res) {
        // Successful authentication, redirect home.
        res.redirect("/success");

    }
);

router.get("/success", passport.authenticate('spotify'), (req, res) => {
    res.send("success")

});

1 Ответ

0 голосов
/ 05 апреля 2020

Одна очевидная вещь, которую я вижу в коде:

 const User = new SpotifyUser == ({
                        spotifyID: spotifyID,
                        displayName: displayName,
                        email: email,
                        profileURL: profileURL,
                        accessToken: accessToken,
                        refreshToken: refreshToken,
                        country: country,
                        accountType: accountType
                    })

Удалите ==

const User = new SpotifyUser({
                        spotifyID: spotifyID,
                        displayName: displayName,
                        email: email,
                        profileURL: profileURL,
                        accessToken: accessToken,
                        refreshToken: refreshToken,
                        country: country,
                        accountType: accountType
                    })
...