mongoose 中的十进制/浮点数,用于 node.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5605551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:00:36  来源:igfitidea点击:

Decimal / Float in mongoose for node.js

mongodbnode.jsmongoose

提问by Luc

I start my first test app on node.js / mongoDB / mongoose, this is a very simple app that aims to crate record in DB and retrieve them.

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

I create a model like:

我创建了一个模型,如:

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

This is working fine, except that I would like to be able to provide a float value for speed instead of the integer one. I gave a try to Decimal and Float but none of them are working. I did not find in the documentation either.

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

Any idea ?

任何的想法 ?

回答by Andrew Orsich

I've searched a bit and found this article stating thatfor storing float values you must use Numbertype. You can store any float value in speedfield.

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

回答by Muzaffar Mahmood

回答by shamanSK

While the mongoDB fully supports float type, the mongoose supports only type of Number which is integer. If you try to save to mongoDB float number using mongooses type of Number it will be converted to string.

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

To sort this out, you will need to load some plugin for mongoose which will extend its value types. There are some plugins which work best with currencies or dates, but in your case I would use https://www.npmjs.com/package/mongoose-double.

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

Your model after changes would look something like this:

更改后的模型如下所示:

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

Hope it helps.

希望能帮助到你。