为什么 mongoose 向 return 我填充了一个非法数组以及如何处理它?

Why mongoose populate return me an illegal array and how to do with it?

我使用 mongoose 填充数据列表,例如:

 Account.findOne({_id:accountId}).populate({
            path:"orders.order",
            match:{_id:orderId},
            selecte:'',
            options:{
              limit:1
            }
          }).exec(function (err, doc) {
              if (err) {
                callback(err);
              }
              callback(doc);
          })
        }

以及我得到的:

[ { order: null },
  { order: null },
  { order: null },
  { order: null },
  { order: null },
  { order: null },
  { order: 
     { date: Tue May 31 2016 12:56:36 GMT+0800 (HKT),
       dishs: [Object],
       __v: 0,
       message: 'plz deliver after 5 p.m',
       price: 5,
       address: [Object],
       shop: null,
       user: 574bfebc29cf722c17f8eafe,
       _id: 574d198451615ce01a5e1a81 } } ]

我认为这个数据是一个数组,但是

                console.log(typeof doc.orders);//object
                console.log(doc.orders.length);//undefined
                console.log(doc.orders[0].order);//error
                console.log(Array.isArray(doc.orders));//false

我不知道如何删除此数据的空值以及如何将此数据更改为数组?

顺便说一句,我在gist中找到一个post说猫鼬populate.match如果不符合条件就会return空值,是真的吗?

我错误地定义了模式。

错误的架构:

orders:{order: [{type: mongoose.Schema.Types.ObjectId, ref:'Order'}] }

在要填充的数组中定义模式的正确方法:

orders:{type:[{
  order:{type: mongoose.Schema.Types.ObjectId, ref:'Order'}
}]}

在此之后,使用 populate.match 会给你一个合法的数组,你可以像普通数组一样使用它。