model.save(function (err)) is not working properly. #4889

Closed
rahulkulmi opened this Issue Jan 11, 2017 · 15 comments

Projects

None yet

2 participants

@rahulkulmi

I am using "version": "4.6.4"
For mongodb i am using mongodb atlas service.

Using this function i am getting issue:

Error\n at model.wrappedPointCut [as save]

Tank.findById(id, function (err, tank) {
if (err) return handleError(err);

tank.size = 'large';
tank.save(function (err, updatedTank) {
if (err) return handleError(err);
res.send(updatedTank);
});
});

Is there the version issue or some thing else. Please let me know if this is version related.

Do you want to request a feature or report a bug?

What is the current behavior?

If the current behavior is a bug, please provide the steps to reproduce.

What is the expected behavior?

Please mention your node.js, mongoose and MongoDB version.

@varunjayaraman
Collaborator

@rahulkulmi, this works for me with the following specs:

node v6.9.2
mongoose 4.6.4
mongodb 3.2

const mongoose = require('mongoose');

const GITHUB_ISSUE = `gh-4889`;

const TankSchema = new mongoose.Schema({
  size: String
});

const Tank = mongoose.model('Tank', TankSchema);

const db = mongoose.connect(`mongodb://localhost:27017/${GITHUB_ISSUE}`);

exec();

function handleError(error) {
  console.error(`Error ${error}\n${error.stack}`);
  process.exit(2);
}

function exec() {
  Tank.create({ size: 'small ' }, (error1, newTank) => {
    if (error1) {
      return handleError(error1);
    }

    Tank.findById(newTank._id, (error2, foundTank) => {
      if (error2) {
        return handleError(error2);
      }

      foundTank.size = 'large';

      foundTank.save((error3, updatedTank) => {
        if (error3) {
          return handleError(error3);
        }

        console.log('Successfully saved tank');
        process.exit(0);
      });
    });
  });
}

Can you post the full code snippet that youre using (and please wrap it in 3 backticks (```), it's difficult to reason about your code when it's not formatted) and the full error message/stacktrace?

@rahulkulmi
rahulkulmi commented Jan 13, 2017 edited
  1. Here User is my mongoose model.
  2. genUpdatedDate is helper function.
  3. When i am run this code on my local system then don't get exception but on server it will show the error (Error\n at model.wrappedPointCut [as save]).
  4. I am try to use code snippet but when i save it it is show all code is same line. So i am not able to do formatted code.

var mongoose = require('mongoose')
var userSchema = new mongoose.Schema({
phone_number: { type: Number },
timestamps: {
created: { type: Date },
updated: { type: Date },
last_used: { type: Date }
}
})
module.exports = mongoose.model('User', userSchema)

User.findById(user_id, function(err, userRes) {
if (err) return console.error(err.stack)
// Check that a user was found
if (userRes === undefined || userRes === null) {
console.log('user is not available in database.')
} else {
helper.genUpdatedDate(function(helperRes) {
userRes.timestamps.last_used = helperRes
})
userRes.save(function(err) {
if (err) console.error(err.stack)
// Do not Check user info
return callback()
})
}
})

@varunjayaraman
Collaborator

Can you please format your code properly? Wrap it in 3 backticks (```): https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code

Also can you post the full stack trace of your error?

What version of node and mongoose are you using on your server?

@rahulkulmi
rahulkulmi commented Jan 13, 2017 edited

Node version = v6.9.2
mongoose version = V4.6.4

Error log:

Error\n at model.wrapped PointCut [as save] (/node_modules/mongoose/lib/document.js:1938:27)\n at app/util/routes_helper.js:384:16\n at Query. (/app/node_modules/mongoose/lib/model.js:3357:16)\n at /app/node_modules/kareem/index.js:259:21\n at /app/node_modules/kareem/index.js:127:16\n at _combinedTickCallback (internal/process/next_tick.js:67:7)\n at process._tickDomainCallback (internal/process/next_tick.js:122:9)"

@varunjayaraman
Collaborator
varunjayaraman commented Jan 13, 2017 edited

What do you mean it's all on the same line? Are you using a text editor or IDE? Just copy it as it is formatted from your project and github should preserve the spacing and such.

Anyway, I've reformatted it below so I and potentially others can take a look more easily:

var mongoose = require('mongoose')
var userSchema = new mongoose.Schema({
  phone_number: { type: Number },
  timestamps: {
    created: { type: Date },
    updated: { type: Date },
    last_used: { type: Date }
  }
})
module.exports = mongoose.model('User', userSchema)

User.findById(user_id, function (err, userRes) {
  if (err) return console.error(err.stack)
  // Check that a user was found
  if (userRes === undefined || userRes === null) {
    console.log('user is not available in database.')
  } else {
    helper.genUpdatedDate(function (helperRes) {
      userRes.timestamps.last_used = helperRes
    })
    userRes.save(function (err) {
      if (err) console.error(err.stack)
      // Do not Check user info
      return callback()
    })
  }
})

error

Error\n at model.wrapped PointCut [as save] (/node_modules/mongoose/lib/document.js:1938:27)\n at app/util/routes_helper.js:384:16\n 
at Query. (/app/node_modules/mongoose/lib/model.js:3357:16)\n 
at /app/node_modules/kareem/index.js:259:21\n 
at /app/node_modules/kareem/index.js:127:16\n 
at _combinedTickCallback (internal/process/next_tick.js:67:7)\n 
at process._tickDomainCallback (internal/process/next_tick.js:122:9)"
@varunjayaraman
Collaborator

Also this code snippet isn't complete. What is callback? And can you show what helpers.genUpdatedDate does? Please post a full reproducible code snippet.

Also it seems like the error can be traced to routes_helper.js line 384. Is this code from routes_helper.js?

@rahulkulmi

helpers.genUpdatedDate code is below here.

module.exports.genUpdatedDate = function(callback) {
var now = new Date()
var dateFormat = require('dateformat')
return callback(dateFormat(now, "yyyy-mm-dd h:MM:ss"))
}

Also I have put code from routes_helper.js line 384. which is i have mention about comment.
And here i have put error code which is got from server that.
Here i have copy code from file and past it here. And also i am using callback in function i am not using promise in my code.

@varunjayaraman
Collaborator
varunjayaraman commented Jan 13, 2017 edited

I still don't understand why you are unable to format your code properly. Are you not copying your code from a text editor? All you have to do is wrap your code in (```)

And I know what a callback is. I'm specifically asking about this snippet:

userRes.save(function (err) {
      if (err) console.error(err.stack)
      // Do not Check user info
      return callback()
 })

callback is undefined here unless you defined it above.

Also, it looks like in your schema that timestamps.last_used is of type Date. Take a look at this snippet:

helper.genUpdatedDate(function (helperRes) {
      userRes.timestamps.last_used = helperRes
})

helperRes is a function is it not? It looks like you're storing a function on a Date field.

@rahulkulmi

Here I am using async.series function so i have add callback in starting for function like this

async.series([
// Get Updated Date and Time for time stamps.
function(callback) {
helper.genUpdatedDate(function(helperRes) {
updatedTime = helperRes
return callback()
})
} ], function(err) {})
Here i am not put all the code i am put the code which is i am getting error.

userRes.save(function (err) {
if (err) console.error(err.stack)
// Do not Check user info
return callback()
})

Also timestamps.last_used is Date formate and my helperRes is also return Date formate.

@rahulkulmi

It's ok no problem i have update my code and now i am using (User.findByIdAndUpdate) method and remove (User.findById and userRes.save) method.

So now my problem is resolve and my code is working fine.

Thanks for reply

@varunjayaraman
Collaborator

All you have to do to format your code is put 3 of these characters: ` on the beginning line and on a newline after the code. If I do it, so can you. Please see the link I posted above: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code Formatting your code makes our lives much easier.

And I don't understand, you've changed your snippet now:

helper.genUpdatedDate(function(helperRes) {
    updatedTime = helperRes
     return callback()
})

Before, it was:

helper.genUpdatedDate(function (helperRes) {
      userRes.timestamps.last_used = helperRes
})

What is updatedTime?

And you did not understand what I meant. helperRes is a function but you are not invoking it when you set userRes.timestamps.last_used equal to it.

Your function helper.genUpdatedDate is a function that takes a function as a parameter. That function is called helperRes.

In this line:

userRes.timestamps.last_used = helperRes

You are setting last_used equal to a function. You have to invoke helperRes if you want to get the return value from inside it that would be a date.

@varunjayaraman
Collaborator

By using findByIdAndUpdate you're actually masking your problem by bypassing validation. Your code is wrong because you are storing a function on a Date field

@rahulkulmi

Yes now i have update my code.
updatedTime is a var field which is define in above the async.series function.

So you are told me that i have to update this code to this way

helper.genUpdatedDate(function (helperRes) {
    userRes.timestamps.last_used = helperRes
})

helper.genUpdatedDate(function (helperRes
     userRes.timestamps.last_used = helperRes
) {})

Like that am i right ?

@varunjayaraman
Collaborator

Thank you for finally formatting your code.

And No, that's invalid JavaScript.

Your genUpdatedDate function looks like this:

module.exports.genUpdatedDate = function(callback) {
    var now = new Date()
    var dateFormat = require('dateformat')
    return callback(dateFormat(now, "yyyy-mm-dd h:MM:ss"))
}

so helperRes needs to be invoked on the return value from dateFormat being invoked on a Date object. The way you've written your code now makes this impossible because helperRes has to take a parameter.

A better way to write it would be like this:

module.exports.genUpdatedDate = function(dateModifier) {
    var now = new Date()
    var dateFormat = require('dateformat')
    return dateModifier(dateFormat(now, "yyyy-mm-dd h:MM:ss"))
}

Then, in your code:

userRes.timestamps.last_used = helper.genUpdatedDate(helperRes);
@rahulkulmi

Now i update my code as per you suggest me.

Thank you for give me your support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment