MongoDB: I want to store array object in collection

邮差的信 提交于 2021-01-21 11:15:47

问题


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:


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


来源:https://stackoverflow.com/questions/42173127/mongodb-i-want-to-store-array-object-in-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!