Ludwig Bossle
Ludwig Bossle

Reputation: 367

Mongoose use float as key

I'm trying to use floats as keys in a mongodb database since I have to store the respective amount of each money value (e.g. 0.01: 10). But when I try saving the data via mongoose (node server using express) it only saves the data with normal (String) keys in the db.

This is my schema:

var ProtokollSchema = new Schema({
"date": String,
"0.01": {type: Number, default: 0},
"0.02": {type: Number, default: 0},
"0.05": {type: Number, default: 0},
"0.10": {type: Number, default: 0},
"0.20": {type: Number, default: 0},
"0.50": {type: Number, default: 0},
"1.00": {type: Number, default: 0},
"2.00": {type: Number, default: 0},
...

});

This is the express function setting the data:

    .post(function(req, res) {
    var protokoll = new ProtokollSchema();
    protokoll["date"] = req.body["date"];
    protokoll["0.01"] = req.body.data["0.01"];
    protokoll["0.02"] = req.body.data["0.02"];
    protokoll["0.05"] = req.body.data["0.05"];
    protokoll["0.10"] = req.body.data["0.10"];
    protokoll["0.20"] = req.body.data["0.20"];
    protokoll["0.50"] = req.body.data["0.50"];
    protokoll["1.00"] = req.body.data["1.00"];
    protokoll["2.00"] = req.body.data["2.00"];
    ...

    protokoll.save(function(err) {
        if (err) res.json(err);
        res.json({ message: "Comment successfully added!"});
    });
})

Is there a solution or is it just not possible to do?

Upvotes: 0

Views: 468

Answers (2)

Ludwig Bossle
Ludwig Bossle

Reputation: 367

The actual problem was that MongoDB simply doesn't support dots in its keys (see this question) Initially I thought the problem was the Schema of mongoose but obviously it wasn't.

Upvotes: 0

Henry Leu
Henry Leu

Reputation: 2274

  1. All keys in a schema must be a string whatever the key string looks like a normal string, a float or others.

  2. Make sure that req.body.data be really with values like {"0.01": xxx, "0.02": xxx, ...};

  3. You should use Model to create a document instead of Schema

    //wrong way
    var protokoll = new ProtokollSchema();
    
    //Right way - Use the schema to generate a model and use model to new a docuemnt.
    var Protokoll = mongoose.model('Protokoll', ProtokollSchema);
    var protokoll = new Protokoll({"0.01": xxx, "0.02": xxx, ...});
    

Upvotes: 1

Related Questions