Mongoose的populate()方法返回一个对象数组而不是单个对象。

4

我有一个集合,其中有一个属性引用另一个集合的objectId。

placeSchema = mongoose.Schema({
    name: String,
    category: [{ type: Schema.Types.ObjectId, ref: 'categories' }],
    facilities: [{ type: Schema.Types.ObjectId, ref: 'facilities' }],
});

category ref是指向categories集合的objectId。而facilities ref是指向一个包含多个objectId的数组,这些objectId都属于facilities集合。

当我使用populate方法填充属性时,facilities会变成一个包含多个facilities对象的数组,但category仍然只是一个单一的category

Place.find(query).populate('category').populate('facilities').limit(limit).skip(offset).exec(function(err, data){
    if (err) return handleError(err);
    res.json(data);
});

以下是上述查询的示例:
{
    "_id": "52ff59be70e8f0dfc8358cb4",
    "address": {
        "address_1": "Chambers Street",
        "city": "Edinburgh",
        "postcode": "EH1 1JF"
    },
    "description": "The National Museum of Scotland brings together our rich Scottish heritage with exciting international collections.",
    "loc": {
        "lon": -3.188384,
        "lat": 55.94772
    },
    "name": "National Museum of Scotland",
    "facilities": [
        {
            "_id": "53012d5b65b5e9a35efbb214",
            "name": "Facility One"
        },
        {
            "_id": "53012d6965b5e9a35efbb215",
            "name": "Facility Two"
        }
    ],
    "category": [
        {
            "_id": "52ffbf33605d0c81f36d98e0",
            "name": "Museums",
            "slug": "museums"
        }
    ]
}

这是Mongo数据库中的文档:

{
    "_id" : ObjectId("52ff59be70e8f0dfc8358cb4"),
    "address" : {
        "address_1" : "Chambers Street",
        "city" : "Edinburgh",
        "postcode" : "EH1 1JF"
    },
    "category" : ObjectId("52ffbf33605d0c81f36d98e0"),
    "description" : "The National Museum of Scotland brings together our rich Scottish heritage with exciting international collections.",
    "facilities" : [
        ObjectId("53012d5b65b5e9a35efbb214"),
        ObjectId("53012d6965b5e9a35efbb215")
    ],
    "loc" : {
        "lon" : -3.188384,
        "lat" : 55.94772
    },
    "name" : "National Museum of Scotland"
}

我应该如何填充单个类别引用而不是数组?
1个回答

4

由于您在模式定义中声明了类别字段为数组,因此这是有道理的:

category: [{ type: Schema.Types.ObjectId, ref: 'categories' }]

以下代码应该可以不将它放在数组中(删除[]):
category: { type: Schema.Types.ObjectId, ref: 'categories' }

假设您确实只需要一个类别。

我只是认为它需要一个数组,我实际上并没有想到那决定了结果。唉!谢谢Andreas! - iamjonesy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接