簡體   English   中英

貓鼬為什么將虛擬字段填充為數組而不是單個項?

[英]Why does mongoose populate virtual field as array instead of single item?

我想用貓鼬作為JSON對象將一個對象填充到一個虛擬字段中,但是它總是返回一個包含單個項目的數組。

這是我的方案代碼(包含虛擬字段):

Order.virtual('client', {
    type: 'ObjectId',
    ref: 'User',
    localField: 'clientId',
    foreignField: '_id'
});

這是我的人口統計方法:

Order.findOneAndUpdate({ internalStatus: 2}, { internalStatus: 3 })
    .lean()
    .populate({ path: 'client', select: 'email' })
    .exec(function (err, order) {
        //...
    });

這是我在返回的JSON中收到的內容:

{ _id: 5ad903d90443fe13b8c9061a,
    client: [ { _id: 5b3755fe69635d1e942d00a8, email: 'user@user.com' } ] }

這是我要實現的目標:

{ _id: 5ad903d90443fe13b8c9061a,
    client: { _id: 5b3755fe69635d1e942d00a8, email: 'user@user.com' } }

感謝您的幫助或建議!

在mongoose mongoose@5.0.17中,我看到它們返回為JSON_OBJECT,但是當我升級到mongoose@5.3.0時,它開始重新調整為JSON_ARRAY

您必須在虛擬字段配置中添加“ justOne:true ”:

Order.virtual('client', {
    type: 'ObjectId',
    ref: 'User',
    localField: 'clientId',
    foreignField: '_id',
    justOne : true

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM