0

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?

Ludwig Bossle
  • 367
  • 2
  • 3
  • 18

2 Answers2

1
  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, ...});
    
Henry Leu
  • 2,184
  • 4
  • 22
  • 34
  • Thanks! Now data is saved to the db. But now i've got the problem that mongodb interprets the dots as object keys. I get the structure: 0 > 01, 1>00 and so on. Any idea on how to fix this? – Ludwig Bossle Dec 16 '17 at 14:43
  • Okay found an answer to this: https://stackoverflow.com/questions/12397118/mongodb-dot-in-key-name – Ludwig Bossle Dec 16 '17 at 14:55
0

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.

Ludwig Bossle
  • 367
  • 2
  • 3
  • 18