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\",\
1
  • So what is the problem you are experiencing? What did you try? Commented Feb 11, 2017 at 6:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

i am in trouble with this type data: var routerData = { "Attr-26.14559.10":{"type":"octets","value":["0x00000002"]} }
@HardikMandankaa what is the issue?
can you try to replace "routerData" value and test?
@HardikMandankaa did you extend the schema and added "Attr-24.14559.10" field to it?
yes. i added in schema. it is store in collection in this format: ""Attr-26" : { "14559" : { "10" : { "type" : "octets", "value" : [ "0x00000002" ] } } }," I need to it store like other value
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.