将动态值添加到MongoDB嵌入式集合

时间:2016-08-09 01:40:20

标签: mongodb express mongoose

我正在开发一个expressJS应用程序。我有一个嵌入式集合的用户架构。我想知道是否有任何技术可以用来动态发布嵌入式集合。例如:

下面我有" a"嵌入式集合,包含2个值x和y。是否可以动态发布值而不是x和y如果我想发布x --- xn?

var user = mongoose.Schema(
{
_id: {type: String, required:true},
name : String,
a: {
x: {sensor_id: String, sname: String, time:String, value: Number },
y: {sensor_id1: String, sname1: String, time1:String, value1: Number }
},
a1 : {
x: {sensor_id2: String, sname2: String, time2:String, value2: Number},
y: {sensor_id3: String, sname3: String, time3:String, value3: Number }
}});

虽然我想发布值,但我喜欢这样:

var user = new User();
user.a.x.sensor_id = req.body.sensor_id;
user.a.y.sname = req.body.sname;

我想知道是否有一些技巧,所以我可以将任意数量的值发布到嵌入式集合" a"?

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

var user = mongoose.Schema(
{
 _id: {type: String, required:true},
 name : String,
 a:[ {
      x: {sensor_id: String, sname: String, time:String, value: Number },
      y: {sensor_id1: String, sname1: String, time1:String, value1: Number }
  }]
});

然后...... ..

var user = new User();
user.a = [{x:sensor_id},{y:req.body.sensor_id},{x:sensor_id2},{y:req.body.sensor_id2}];