2016-09-23 96 views
0

不工作我具有其中如下所示閔驗證在貓鼬

balance: { 
    type: Number, 
    min: 0, 
    default: 30 
} 

我已設置0作爲最低值,以使平衡不會是負值的餘額字段聲明一個Schema。但是當我通過更新查詢遞減餘額值時,餘額變成負值。

我的更新查詢:

User.update({ 
    _id: mongoose.Types.ObjectId(id) 
}, { 
    $inc: { 
     balance: -10 
    } 
}, function(error, result) { 
    // code 
}); 

難道我做的代碼什麼錯誤?

回答

2

貓鼬驗證是一個內部的中間件這不叫上更新;如果你想強制更新驗證,你應該找到文檔,更新屬性並保存。

例如:

User.findById(id, function(err, result) { 
    if (err) return handleError(err); 
    user.balance = -10; 
    user.save(function(err) { 
    if (err) return handleError(err); 
    ... 
    }); 
}); 
4

默認情況下,mongoose不會在更新調用中生效,但有一個選項可用。看看貓鼬文檔:http://mongoosejs.com/docs/validation.html(更新校驗)

var opts = { runValidators: true }; 
Toy.update({}, { color: 'bacon' }, opts, function (err) { 
    assert.equal(err.errors.color.message, 
    'Invalid color'); 
}); 
0

啓用上更新驗證使用findByIdAndUpdate(這是默認禁用)是這樣的:

User.findByIdAndUpdate(id, { 
    $set: attributes, 
}, { 
    new: true, 
    runValidators: true, 
}) 
.then((user) => { 
    if (!user) { 
    // user not found 
    } 

    console.log(user); 
}) 
.catch(e => console.log(e));