Ginxxx
Ginxxx

Reputation: 1648

mongoose save to 2 collection

Hello guys i really need help for this one . It's been bugging me for how many days

model/user.js

var UserSchema = mongoose.Schema({
username:{
    type: String,
    unique: true,
    index:true
},
password:{
    type:String
},
email:{
    type:String,
    required: true
    // unique: true
},
authToken:{
    type: String,
    required: true,
    unique: true
},
IsAuthenticated:{
    type: Boolean,
    required: true
},
name:{
    type:String
},
field:{
    type:String
},
e_money:{
    type:Number //this is the integer form in mongoose
}
});


//accesible variable from the outside
var User = module.exports = mongoose.model('users', UserSchema);

var InfoUser = module.exports = mongoose.model('infouser', UserSchema);

and how i save is like this

var User = require('../models/user);

 var newUser = new User({
        name: name,
        email: email,
        authToken: authToken,
        IsAuthenticated: false,
        username: username,
        password: password,
        field: field,
        e_money: e_money //temporary emoney

    });

 var newUser2 = new InfoUser({
        name: name,
        email: email,
        authToken: authToken,
        IsAuthenticated: false,
        username: username,
        password: password,
        field: field,
        e_money: e_money //temporary emoney

    });




        //save the newly created user to database
    User.createUser(newUser,function(err, user){
        if(err) throw err;
        console.log(user);
   )};

   User.createUser(newUser2,function(err,user){
    if(err) throw err;
        console.log(user);
   )};

What is the problem it always says that the infouser is not defined. Can someone plase

Upvotes: 1

Views: 473

Answers (1)

Andrew Lively
Andrew Lively

Reputation: 2153

The problem is that you are exporting two different models through the same module.exports. Instead I would recommend that you export them separately:

model/user.js

// You can add instance methods like this:
UserSchema.methods.createUser = function(user) {
  // Whatever you want to do here
};

var User = mongoose.model('users', UserSchema);
var InfoUser = mongoose.model('infouser', UserSchema);

exports.User = User;
exports.InfoUser = InfoUser;

/*
  You could also do this as:
  module.exports = { User: User, InfoUser: InfoUser };
*/

Then when you want to use them:

var User = require('../models/user').User;
var InfoUser = require('../models/user').InfoUser;

Upvotes: 2

Related Questions