Jenny Mok Jenny Mok - 28 days ago 4
Javascript Question

mongoose save is not a function using schema

I got StripeToken.save is not a function error with below code. That's my model, I wonder what went wrong, it looks ok to me.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var stripe_token_schema = new Schema({
email: String,
token: String,
used: {type: Date, default: 0}
});

var StripeToken = module.exports = mongoose.model('stripe_token', stripe_token_schema);

module.exports.save_token = function(email,token){
StripeToken.save({email:email,token:token}).exec(callback); //error here
}

Answer

Your model seems to be correct

model-schema.js:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var stripe_token_schema = new Schema({
    email: String,
    token: String,
    used: {type: Date, default: 0}
});

module.exports = mongoose.model('stripe_token', stripe_token_schema);

But you should change your .save() function

postNewMail.js

require('mongoose');
var MailModel= require('./model-schema.js');

. . .

var newMail = {
                email: "fakemail@gmail.com",
                token: "yourGeneratedToken"
};

saveNewUser(newMail).then( function( response ){
  if(response.error){
    console.log(response.error);
  } else {
    console.log('Successfully saved ', response);
  }
});

function saveNewUser(email){
  return new Promise( function (resolve, reject) {
    // Creates a new Email based on the Mongoose schema
    var newEmail= new MailModel(email);
    // New Geometry is saved in the db.
    newEmail.save(function(error) {
        console.log('err',error);
        if (error){
            return reject({error : 'Error while saving email'});
        }
        // If no errors are found, it responds with a JSON of the new email
        return resolve(email);
    });
  });
}

If you have other troubles, please, share your server.js or whenever you initialized your connection to MongoDB.

Hope I've been helpful.