DZarrillo
DZarrillo

Reputation: 31

ReferenceError saving data to mongodb using mongoose in node.js

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);

Upvotes: 2

Views: 3896

Answers (2)

DZarrillo
DZarrillo

Reputation: 31

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);
    
    }
    

Upvotes: 0

pkoulianos
pkoulianos

Reputation: 177

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;
});

Upvotes: 1

Related Questions