【问题标题】:Mongoose populate() returns array of objects instead of single objectMongoose populate() 返回对象数组而不是单个对象
【发布时间】:2014-03-24 10:27:23
【问题描述】:

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

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

category 引用是 categories 集合的 objectId。 facilities ref 是 facilities 集合的 objectId 的数组。

当我填充属性时,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"
}

如何填充我的单个 category 引用而不是数组?

【问题讨论】:

    标签: javascript node.js mongodb orm mongoose


    【解决方案1】:

    这是有道理的,因为您在架构定义中已将类别字段声明为数组:

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

    以下应该可以不将其放入数组中(删除[]):

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

    这是假设您确实只想要一个类别。

    【讨论】:

    • 我只是认为它需要一个我实际上并不认为决定结果的数组。嗬!谢谢安德烈亚斯!
    猜你喜欢
    • 1970-01-01
    • 2017-11-17
    • 2021-11-24
    • 1970-01-01
    • 2020-05-06
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    相关资源
    最近更新 更多