首页 > mongoose 如何在sub doc 中插入数组?

mongoose 如何在sub doc 中插入数组?

schema如下:

  var AccountSchema = new mongoose.Schema({
    email:     { type: String, unique: true },
    password:  { type: String},
    location: {type: [{
      name: { type: String},
      loc:{type:[Number]}
    }]},
    order:{type:[{
      date:{type: Date,default: Date.now},
      dishs:{type: [{
        shopId:{type: String},
        itemId:{type: String},
        amount:{type: Number}
      }]},
      userId:{type: String},
       comment:{type:[{
         date:{type: Date,default: Date.now},
         userId:{type: String},
         content:{type: String}
       }]} 
    }]}
  });


  

对于location,可以在node.js的router中循环下面的函数来尽心批量插入,实际上在mongoose这边是每次都单个插入的。


    var addLocation = function(accountId, locationName, coordinate, callback) {
        Account.update({_id:accountId}, {$push: {location:{
          "name" : locationName,
          "loc" : coordinate
        }}},{upsert:true},
      function (err) {
        callback(err);
    });
}

但是对于order应该怎么处理呢,因为order里面的dishs字段是一个array,我想达到这个目的:

  Account.update({_id:accountId}, {$push: {order:{
          "userId" : accountId
          "dishs" :
          for(var i=0;i<dish.length;i++){
              "shopId" = dish[i].shopId,
              "itemId" = dish[i].itemId,
              "amount" = dish[i].amount,
          }
        }}},{upsert:true},
      function (err) {
        callback(err);
    });
【热门文章】
【热门文章】