2013-04-09 37 views
1

下面是模型定義:貓鼬更新一個字段爲空值拋出異常

pricing: { type: Number, default: null } 

這是我得到的,當貓鼬嘗試更新與源數據是空的紀錄除外:

錯誤消息我:

message: 'Cast to number failed for value "NaN" at path "pricing"', 
    name: 'CastError', 
    type: 'number', 
    value: NaN, 
    path: 'pricing' 

我需要更新與空的現有值此情況下,由於應用治療領域是一個爲空的號碼字段。

如何解決?提前致謝!

+0

我不認爲這是Mongoose和MongoDB 2.6的問題。我不知道什麼時候修復了,但是我測試了'model.create()'爲空值,模式缺省值爲空值,'doc.save()'爲空值,並且它們都正確插入, find()'那個空值。 – Nucleon 2014-07-02 18:32:21

回答

0

我的猜測是它試圖將null轉換成Number。嘗試將default設置爲0;

+0

謝謝。我試過了。它不起作用。我更新了我得到的錯誤消息。 – zsong 2013-04-09 21:01:32

0

爲價格插入空值似乎對我來說沒問題;看我下面使用的示例代碼:

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; 

通過您的錯誤信息來看,它會出現一個無效的計算正在進行中,其結果是試圖插入到Mongo中。錯誤消息中的「值」是試圖插入的值。

var testInvalid = new Widget({ name: "Invalid Test", price: "abc"}); 

這將導致:

{ message: 'Cast to number failed for value "abc" at path "price"', 
    name: 'CastError', 
    type: 'number', 
    value: 'abc', 
    path: 'price' } 

他們是任何更多的細節,或者你可以共享代碼示例,您可以通過嘗試保存下列文件驗證這一點?

編輯:

我會嘗試從您的代碼的其他部分隔離的更新,看是否可以複製錯誤,就像這樣:

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

此隔離更新似乎對工作我。對不起,我不能有更多的幫助:/

+0

謝謝你的回覆。插入是Okey,但不能更新。我使用findOne獲取文檔並將其中一個字段賦值爲null,然後調用save()。我得到了那個錯誤信息。 – zsong 2013-04-09 23:57:16

0

NaN!= null是描述問題的最佳方式。 您應該檢查您嘗試爲「NaN」插入的價格的價值。 如果此測試爲true,則在您的文檔中插入一個空值,否則插入正確解析的定價(作爲數字)。