drudge/mongoose-findorcreate

How to import with type: "module" in Node.js

Closed this issue · 8 comments

I'm using Node.js for the Backend of my app, and I want to implement this package.

I want to know how to write the proper import statement (using type: "module"). I think it is:

import findOrCreate from "mongoose-findorcreate";

But for some reason VSCode marks it as a warning. Can someone tell me how is the proper import statement?

binki commented

I bet that mongoose-findorcreate is a CommonJS module. If you use import x from 'module', then the module 'module' must have an export named default which will be assigned to x. However, a CommonJS module normally does not have an export named default. The warning you are getting from VS Code is likely that there is no default export from the module.

Instead, you likely want to do import * as findOrCreate from 'mongoose-findorcreate';.

Please try this and let us know if that works!

I bet that mongoose-findorcreate is a CommonJS module. If you use import x from 'module', then the module 'module' must have an export named default which will be assigned to x. However, a CommonJS module normally does not have an export named default. The warning you are getting from VS Code is likely that there is no default export from the module.

Instead, you likely want to do import * as findOrCreate from 'mongoose-findorcreate';.

Please try this and let us know if that works!

Thanks a lot for the explanation! Both ways work and don't affect the functionality, it still runs without errors. But the warning persists.

I attach an image of the warning here:

mongoose-findorcreate warning

binki commented

@naufragotech The issue is that you’re using TypeScript. If you use JavaScript, you will not get a warning like that. If you are using TypeScript, it is your responsibility to understand what that means when consuming a package which is JavaScript and does not provide its own typings (such as mongoose-findorcreate).

@binki I'm not using TypeScript. You can see my entire code below:

`//jshint esversion:6
import "dotenv/config";
import express from "express";
import ejs from "ejs";
import mongoose from "mongoose";
import session from "express-session";
import passport from "passport";
import passportLocalMongoose from "passport-local-mongoose";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import findOrCreate from "mongoose-findorcreate";

const app = express();

app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: true }));

app.use(session({
secret: "Secret testing",
resave: false,
saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb://localhost:27017/userDB", { family: 4 });

const userSchema = new mongoose.Schema({
username: String,
password: String,
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "https://localhost:3000/auth/google/secrets",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function (accessToken, refreshToken, profile, cb) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));

app.get("/", (req, res) => {
res.render("home");
});

app.get("/auth/google", passport.authenticate('google', {

scope: ['profile']

}));

app.get('/auth/google/secrets',
passport.authenticate('google', { failureRedirect: '/login' }),
function (req, res) {
// Successful authentication, redirect home.
res.redirect('/secrets');
});

app.route("/login")
.get(async (req, res) => {
res.render("login");
})

.post(async (req, res) => {
    const user = new User({
        username: req.body.username,
        password: req.body.password
    });

    req.login(user, function (err) {
        if (err) {
            console.log(err);
        } else {
            passport.authenticate("local")(req, res, function () {
                res.redirect("/secrets");
            });
        }
    })

});

app.route("/register")
.get(async (req, res) => {
res.render("register");
})

.post(async (req, res) => {

    User.register({ username: req.body.username }, req.body.password, function (err, user) {
        if (err) {
            console.log(err);
            res.redirect("/register");
        } else {
            passport.authenticate("local")(req, res, function () {
                res.redirect("/secrets");
            });
        }
    });

});

app.get("/secrets", (req, res) => {
if (req.isAuthenticated()) {
res.render("secrets");
} else {
res.redirect("/login");
}
});

app.get("/logout", function (req, res) {
req.logout(function (err) {
if (err) {
console.log(err);
} else {
res.redirect("/");
}
});
});

app.listen(3000, () => {
console.log("Server started on port 3000.");
});`

binki commented

The error you posted is a TypeScript error. You need to learn/understand how vscode works: https://code.visualstudio.com/docs/nodejs/working-with-javascript . This is not a support forum for vscode. Sorry!

Thanks a lot for the reference link and for taking the time to answer! I'm kind of new in Web Development so I appreciate very much your help.

binki commented

Yes, there are a lot of technologies that come together for web development, so it is not always clear where errors come from. Do let us know if you encounter any issue with this plugin behaving incorrectly. We will help as we have time (which is a very scarce resource x.x).

@naufragotech updating the /auth/google route to
app.get('/auth/google',
passport.authenticate('google', {
scope: ['profile', 'email']
})
);

will help resolve the issue!