2

I get array object from front side, and want to save it in collection using NodeJS, Mongodb.

My object is:

routerData={"User-Name":
    {"type":"string","value":["\u0000\u0000\u0000\u0000"]},
"NAS-IP-Address":
    {"type":"ipaddr","value":["10.1.0.1"]}
},

My collection schema is:

var model = new Schema({
routerData:{
    "User-Name": {
        "type": String,
        "value": []
    },
    "NAS-IP-Address": {
        "type": String,
        "value": []
    },

},
});

I am trying with this code:

var obj = new objModel(req.body);
obj.routerData = req.body.routerData;
obj.save(function (err, result) {

});

i am getting this error:

"message": "Cast to Object failed for value \"{\"User-Name\":{\"type\":\"string\",\
Hardik Mandankaa
  • 3,129
  • 4
  • 23
  • 32

1 Answers1

4

If you want to have a property named 'type' in your schema you should specify it like this 'type': {type: String}.

Also your value arrays should have type: "value": [String]

Here is a working example.

'use strict';

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema;

var schema = new Schema({
 routerData: {
  'User-Name': {
   'type': {type: String},
   'value': [String]
  },
  'NAS-IP-Address': {
   'type': {type: String},
   'value': [String]
  },

 },
});

var RouterData = mongoose.model('RouterData', schema);

var routerData = {
 'User-Name': {'type': 'string', 'value': ['\u0000\u0000\u0000\u0000']},
 'NAS-IP-Address': {'type': 'ipaddr', 'value': ['10.1.0.1']}
};

var data = new RouterData({routerData: routerData});
data.save();
Antonio Narkevich
  • 4,206
  • 18
  • 28