2

I'm trying to save to a user collection in mongodb using mongoose and I'm getting the following

Error: ReferenceError: Cannot access 'user' before initialization.

const user = mongoose.model("users");

try {
        const user = await new user({
          googleId: profile.id,
          name: profile.displayName,
          email: profile.emails[0].values
        }).save();

        done(null, user);
      } catch (err) {
        console.log("error " + err);
      }
    }  

Here is my user.js file:

 const mongoose = require("mongoose");
 const { Schema } = mongoose;

 const userSchema = new Schema({
     googleId: String,
     name: String,
     email: String
 });

 mongoose.model("users", userSchema);
1
  • In your first code snippet, you need to import the users object form user.js model file. Can you please share the whole codebase of the first code snippet and also the folder structure? Commented Jan 17, 2020 at 5:07

2 Answers 2

1

You have to export your model schema : user.js

let mongoose = require("mongoose");

// User Schema
let userSchema  = mongoose.Schema({
     googleId: String,
     name: String,
     email: String
});

let User = module.exports = mongoose.model("users", userSchema);

index.js

// User model must be in same directory
const User = mongoose.model("users");

const user = new User();
//add model proporties
user.googleId = profile.id;
user.name = profile.displayName;
user.email = profile.emails[0].values;
//save user to db
user.save(function (err, data) {
    if (err) {
      console.log(err);
      res.send(err.message);
      return;
    }
    res.send('success');
    return;
});
Sign up to request clarification or add additional context in comments.

1 Comment

I had a small typo at my code snippet , try again if you like.
0

Thanks for your help I got the following solution from two users on discord: @Lumeey & @Korbook:

  1. model user.js was changed to the following :

    const mongoose = require("mongoose");
    const { Schema } = mongoose;
    
    const userSchema = new Schema({
      googleId: String,
      name: String,
      email: String
     });
    
    module.exports = mongoose.model("Users", userSchema);
    
  2. In my passport.js :

    const User = require("../models/user");
    
    try {
        const user = await User.create({
         googleId: profile.id,
         name: profile.displayName,
         email: profile.emails[0].value
       });
    
       done(null, user);
    } catch (err) {
       console.log("error " + err);
    
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.