Here is the model definition:
pricing: { type: Number, default: null }
this is the exception I get when Mongoose tries to update a record with the source data being null:
Error message I got:
message: 'Cast to number failed for value "NaN" at path "pricing"',
name: 'CastError',
type: 'number',
value: NaN,
path: 'pricing'
I do need to update the existing value with null for this case since the application treat the field to be a null-able Number field.
How to fix it? Thanks in advance!
My guess is that it is trying to cast null to a Number. Try setting the default to 0;
Inserting null values for pricing seems to work okay for me; see the sample code I used below:
app.js
var mongoose = require("mongoose"),
Widget = require("./model.js").model;
// connect to mongo
mongoose.connect("mongodb://localhost/testdb");
// test insertion
var testValid = new Widget({ name: "Valid Test", price: 10.00 }),
testInvalid = new Widget({ name: "Invalid Test", price: null });
testValid.save();
testInvalid.save(function (err) {
if (err) {
console.log(err);
}
});
model.js
var mongoose = require("mongoose");
var schema = new mongoose.Schema({
name: String,
price: { type: Number, default: null }
});
exports.model = mongoose.model("Widget", schema);
exports.schema = schema;
Judging by your error message, it would appear that an invalid calculation is being made, the result of which is attempting to insert into Mongo. "value" in the error message is the value that was trying to be inserted. You can verify this by attempting to save the following document:
var testInvalid = new Widget({ name: "Invalid Test", price: "abc"});
Which will result in:
{ message: 'Cast to number failed for value "abc" at path "price"',
name: 'CastError',
type: 'number',
value: 'abc',
path: 'price' }
Are they any more details or code samples you could share?
EDIT:
I would try isolating the update from the rest of your code and seeing if you can duplicate the error, like this:
var mongoose = require("mongoose"),
Widget = require("./model.js").model;
// connect to mongo
mongoose.connect("mongodb://localhost/testdb");
// insert record
var testInvalid = new Widget({ name: "Invalid Test", price: 10.00 });
// update record
testInvalid.save(function (err) {
if (err) {
console.log(err);
} else {
Widget.findOne({ name: "Invalid Test" }, function (err, record) {
// set price to null & save
record.price = null;
record.save(function (err) {
if (err) {
console.log(err);
}
});
});
}
});
This isolated update appeared to work for me. Sorry I can't be of more help :/
NaN != null is the best way to describe the problem. You should check the value of the price you are trying to insert for 'NaN'. If this tests to true then insert a null in your document, otherwise insert the correctly parsed pricing (as a Number).