Hardik Mandankaa
Hardik Mandankaa

Reputation: 3376

MongoDB: I want to store array object in collection

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\",\

Upvotes: 2

Views: 36411

Answers (1)

Antonio Narkevich
Antonio Narkevich

Reputation: 4326

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

Upvotes: 4

Related Questions