简体   繁体   English

猫鼬创建带有分类子文档的新文档

[英]Mongoose create a new document with catergorized sub documents

I've been going through the Mongoose docs, and I think I'm missing some fundamental understanding in how it works. 我一直在研究Mongoose文档,但我想我对它的工作方式缺少一些基本的了解。

What I'm trying to do 我想做什么

I'm making a third party API call that returns a structure that looks like 我正在进行第三方API调用,该调用返回的结构看起来像

Route
 |__Train 1 on Route
     |__Upcoming Station (with ID)
     |   |__Time to this station
     |__Upcoming Station (with ID)
     |   |__Time to this station
     ...
 |__Train 2
        ...

And my goal is to format it in a document as such 我的目标是将其格式化为文档

tableId : String,

stations : [{   
    stopId : String, 
    incoming : [{
        vehicleId : String,
        timeAway : { type: Number, min: 0, max: 3000 },
        lastUpdated : { type: Date, default: Date.now }
    }]
}],

What I'm trying currently is going through the received data for each train, and in that each upcoming station, and plug the estimated arrival time into the list of stations. 我目前正在尝试查看每列火车的接收数据,以及即将到来的每个车站的数据,然后将预计到达时间插入车站列表中。 The important part is that Train 1 and Train 2 may both be arriving at a given station, and I only want one station element with multiple predictions. 重要的是火车1和火车2可能都到达一个给定的车站,我只希望一个具有多个预测的车站元素。 The problem is, I can't do a findOneAndUpdate with an upsert, as the document doesn't exist yet. 问题是,由于文档尚不存在,我无法使用upsert进行findOneAndUpdate。

From the doc on subdocs ( here ), I've tried push and addToSet, but these just create a subdocument for each prediction. 从subdocs的文档( 在此处 )中,我尝试了push和addToSet,但是它们只是为每个预测创建一个子文档。 For example I'll get: 例如,我将得到:

[{
  stopId: 1234,
  incoming : [{
    vehicleId : 11,
    timeAway : 200
  }]
},
  stopId: 1234,
  incoming : [{
    vehicleId : 22,
    timeAway : 400
  }]
}]

Where I'm trying to get: 我要去的地方:

[{
  stopId: 1234,
  incoming : [{
    vehicleId : 11,
    timeAway : 200
  },{
    vehicleId : 22,
    timeAway : 400
  }]
}]

I feel like I'm missing some fundamental aspect of creating this document. 我觉得我缺少创建此文档的一些基本方面。

For data schema, 对于数据模式,

var StationSchema = new mongoose.Schema({
    tableId: String,
    stations: [{
        stopId: String,
        incoming: [{
            vehicleId: String,
            timeAway: {type: Number, min: 0, max: 3000},
            lastUpdated: {type: Date, default:  Date.now}
        }]
    }]
});

Save data through 通过保存数据

var s = new Station({
    tableId: '2'
});

s.save(function(err) {

Result 结果

{ "_id" : ObjectId("56e68bcf851a00680832ef13"), "tableId" : "2", "stations" : [ ], "__v" : 0 }

We know the default value of stations is empty array, which is design behavior of mongoose. 我们知道stations的默认值为空数组,这是猫鼬的设计行为。 The upsert: true will add one new document not for sub-document. upsert: true将为子文档添加一个新文档。

To insert station subdocument, we can first check whether the stopId exists, if not, insert new station subdocument. 要插入工作站子文档,我们首先要检查stopId是否存在,如果不存在,请插入新的工作站子文档。 otherwise, we can insert new incoming subdocument into stations . 否则,我们可以将新的incoming子文档插入stations Here are sample codes 这是示例代码

Station
    .findOneAndUpdate({tableId: '2', 'stations.stopId': {$exists: false}}, 
                     {$addToSet: {stations: {stopId: '1234', incoming: []}}},
                   function (err, doc){
                        if (err)
                            console.log(err);
                        else{
                            Station
                                .findOneAndUpdate( 
                                  {'stations.stopId': 1234}, 
                                  {$addToSet: {'stations.$.incoming': {vehicleId: 22, timeAway: 400}}}, 
                                  function(err, doc) {
                                    if (err)
                                        console.log(err);
                                    else
                                        console.log(doc);
                                  });

                        }
                   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM