如何在猫鼬(mongodb)中存储外键

时间:2015-01-02 09:58:31

标签: node.js mongodb mongoose

我有一个Order表和一个Attempt表。我希望在订单中存储尝试的外键。我用以下方式做事

AttemptSchema.pre('save', function(next) {
    var attempt = this;
    Order.findById(this.order).exec(function(err, order) {
      if (err) next(err);
      if (!order) next(new Error('could not load order with order_id:' + order));
      order.attempts.push({    
        attempt: attempt,
        runsheet: attempt.runsheet
      });
      order.save(function(err){
        if(err) next(err);
        else next();
      });
    });
});

当我打印订单时,它会打印下面的内容。额外的_id和id汇编在哪里。有更好的存储方式吗?

{
  "_id": "54a6522b528f452cebe9268c",
  "attempts": [
    {
      "attempt": "54a65d1721d6802c2b4eb04f",
      "runsheet": null,
      "_id": "54a65d1721d6802c2b4eb050",
      "id": "54a65d1721d6802c2b4eb050"
    }
  ]
}

表的模式如下

var AttemptSchema = new Schema({
  order: {
    type: Schema.ObjectId,
    ref: 'Order',
    required:'true',
    index: true
  },
  runsheet: {
    type: Schema.ObjectId,
    ref: 'Runsheet'
  },
});

var OrderSchema = new Schema({
  attempts: [{
    attempt: {
      type: Schema.ObjectId, 
      ref: 'Attempt'
    },
    runsheet: {
      type: Schema.ObjectId, 
      ref: 'Runsheet'
    }
  }]
});

1 个答案:

答案 0 :(得分:0)

这不是async.series的正确用例,并且没有正确使用。为了遍历一个对象数组,async.each将是一个更好的选择。试试下面,它应该解决你的问题

AttemptSchema.pre('save', function(next) {
    var attempt = this;
    Order.findById(this.order).exec(function(err, order) {
        if (err) next(err);
        if (!order) next(new Error('could not load order with order_id:' + order));
        var isPresent = false;
        async.each(order.attempts, function(each_order_attempt, callback) {
            if (each_order_attempt._id === attempt._id) isPresent = true;
            callback();     //calls the next value of array object
        }, function(err) {  //called finally when all of them are done
            if (!isPresent) {
                order.attempts.push({
                    attempt: attempt,
                    runsheet: attempt.runsheet
                });
            }
            order.save(function(err) {
                if (err) next(err);
                else next();
            });
        });
    });
});