简体   繁体   中英

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM