在模型中使用Decimal类型时抛出异常

时间:2017-08-26 10:10:30

标签: mongoose

以下代码段:

const Promise = require('bluebird');
const mongoose = require('mongoose');

mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost:27017/tutorial', { useMongoClient: true });

var Doc = mongoose.model('Test', new mongoose.Schema({
    x: mongoose.Schema.Types.Decimal
    //x: Number 
}));

Doc.create({ x: '0.1' }).
  then(doc => doc.update({ $inc: { x: '0.2' } }).then(() => doc)).
  then(doc => Doc.findById(doc)).
  then(doc => console.log('doc', doc.toObject())).
  catch(error => console.error(error));
当模型的x字段类型为Decimal时,

会抛出错误,但如果其类型为Number,则会生效。

Mongoose: tests.insert({ x: Decimal128 { _bsontype: 'Decimal128', bytes: <Buffer 01 00 00 00 00 00 00 00 00 00 00 00 00 00 3e 30> }, _id: ObjectId("59a053ffe7ce2302e6d92ee3"), __v: 0 })
{ MongoError: connection 0 to localhost:27017 closed
    at Function.MongoError.create (/mongoose-tut/node_modules/mongodb-core/lib/error.js:29:11)
    at Socket.<anonymous> (/mongoose-tut/node_modules/mongodb-core/lib/connection/connection.js:200:22)
    at Object.onceWrapper (events.js:316:30)
    at emitOne (events.js:115:13)
    at Socket.emit (events.js:210:7)
    at TCP._handle.close [as _onclose] (net.js:549:12)
  name: 'MongoError',
  message: 'connection 0 to localhost:27017 closed' }

还不能使用Decimal类型吗?

MongoDB服务器版本:3.4.7, 猫鼬版:4.11.8, Node.js版本:8.3.0

1 个答案:

答案 0 :(得分:1)

我必须通过输入命令

来设置MongoDB的兼容模式(从3.2升级到3.4之后)
db.adminCommand( { setFeatureCompatibilityVersion: "3.4" } )

在MongoDB shell中作为管理员。

source