Stephen Romero
Stephen Romero

Reputation: 3022

mongoose .exec() doesn't work, but promises do

I am trying to add a new entry into a collection and for some reason I am now getting this error! TypeError: newForm.save(...).exec is not a function

I've followed this answer, but now for some reason it's not working and I ended up switching to en es6 promise and that works fine.

If I can get an explanation if .exec() is even necessary or to stick with a promise for mongoose.

Documentation for .exec() here.

const express = require('express');
const router = express.Router();

const Forms = require('../models/formschema');
const checkAuth = require('../middleware/check-auth');

router.post('/saveForms/',checkAuth,(req,res)=>{
    
    const clientID = res.locals.dataToken.ClientID;

    const formData = req.body;

    newForm = new Forms({
        clientID,
        formData: {
            formName : formData.formName,
            components : JSON.stringify(formData.components)
        }
    }
  // This doesn't work
  newForm.save(newForm).exec(function (err,res){
        if (err) {       
            res.status(200).json(err);
        }
        res.status(200).json(res);
    })
    
  // but this does
  newForm.save().then(result =>{
        console.log(result);
        res.status(200).send(result);
    })
    .catch(err => {
        console.log(err);
        res.status(200).send(err);
    });  

     
});

Forms Schema

const mongoose = require('mongoose');

const formSchema = new mongoose.Schema({
    clientID: Number,
    formData: {
          formName: String, 
          components: String
      }
})

module.exports = mongoose.model('Forms', formSchema);

Upvotes: 1

Views: 1327

Answers (1)

cischa
cischa

Reputation: 424

According to the documentation, save() returns a Promise, not a Mongoose Query.

The reason exec() is used in the referenced answer is because that example executes a query, which returned a Query object. In your code, newForm is a Document and save() returned a Promise. exec() is not relevant in this case.

If the then() syntax is not preferred, you can always pass a callback to save(), as mentioned in the documentation.

Upvotes: 1

Related Questions