58

我在 node.js / mongoDB / mongoose 上启动了我的第一个测试应用程序,这是一个非常简单的应用程序,旨在在 DB 中创建记录并检索它们。

我创建了一个模型,例如:

var Car = new Schema({
    brand : String,
    speed  : Number,
    date  :  { type: Date, default: Date.now }
});

这工作正常,除了我希望能够为速度提供一个浮点值而不是整数值。我尝试了 Decimal 和 Float,但它们都不起作用。我也没有在文档中找到。

任何的想法 ?

4

5 回答 5

83

我搜索了一下,发现这篇文章指出要存储浮点值,您必须使用Numbertype. speed您可以在字段中存储任何浮点值。

于 2011-04-09T20:32:13.753 回答
4

是的,您可以使用该Decimal128类型。

https://mongoosejs.com/docs/api.html#mongoose_Mongoose-Decimal128

于 2019-03-28T11:20:12.307 回答
0

您可以创建您的自定义。像这样

'use strict';

const mongoose = require('mongoose');

class DoubleType extends Number {
  constructor(v) {
    super(v);
    this.value = v;
    this._bsontype = 'Double';
  }

  toBSON() {
    return this;
  }
}

class Double extends mongoose.SchemaType {
  constructor(key, options) {
    super(key, options, 'Double');

    Object.assign(this.$conditionalHandlers, {
      '$lt': val => this.castForQuery(val),
      '$lte': val => this.castForQuery(val),
      '$gt': val => this.castForQuery(val),
      '$gte': val => this.castForQuery(val),
    });
  }

  cast(val) {
    if (val == null) {
      return val;
    }
    if (val._bsontype === 'Double') {
      return new DoubleType(val.value);
    }

    const _val = Number(val);
    if (isNaN(_val)) {
      throw new mongoose.SchemaType.CastError('Double',
        val + ' is not a valid double');
    }
    return new DoubleType(_val);
  }
}

mongoose.Schema.Types.Double = Double;
mongoose.Types.Double = DoubleType;

module.exports = Double;

源代码是从@mongoosejs/double 复制的

于 2020-06-21T07:10:33.940 回答
0

您可以在 Mongoose Schema 中使用Decimal128作为

speed:{
type:mongoose.Types.Decimal128
}

于 2022-01-05T08:48:42.687 回答
-3

虽然 mongoDB 完全支持浮点类型,但 mongoose 仅​​支持整数类型的数字。如果您尝试使用 mongooses 类型的 Number 保存到 mongoDB 浮点数,它将被转换为字符串。

为了解决这个问题,您需要为 mongoose 加载一些插件,该插件将扩展其值类型。有一些插件最适合货币或日期,但在你的情况下,我会使用https://www.npmjs.com/package/mongoose-double

更改后的模型如下所示:

var mongoose = require('mongoose')
require('mongoose-double')(mongoose);

var SchemaTypes = mongoose.Schema.Types;
var Car = new Schema({
    brand: { 
        type: String 
    },
    speed: {
        type: SchemaTypes.Double
    },
    date: {
        type: Date, 
        default: Date.now 
    }
});

希望能帮助到你。

于 2016-02-18T13:00:20.607 回答