更新嵌套数组并在此之前用猫鼬填充

时间:2019-09-10 14:33:04

标签: javascript arrays node.js mongodb mongoose

我想用猫鼬将照片添加到一个国家。但是国家也是一张照片。这是我的用户架构:

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    firstName: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    birthDate: {
        type: Date,
        required: true
    },
    sex: {
        type: String,
        required: true
    },
    countries: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Country',
            photos: [
                {
                    base64: {
                        type: String,
                        required: true       
                    },
                    title: String,
                    description: String
                }
            ]
        }
    ],
    admin: {
        type: Number,
        required: true
    }
});

这是我作为数据输入mongoDB的结果:

enter image description here

问题是我只有国家/地区的ID。我想使用文档国家/地区的另一个字段。当我想获取数据时,填充工作很好,但是如何填充然后使用字段使用mongoDB更新?

此外,我不知道如何将数据更新为嵌套数组,我尝试过:

User.findOneAndUpdate(
    {
        "name": "CHARLAT",
        "countries": "5d2d847b06f2f94118a36518"
    },
    { $push : { "countries.photos" : {
        base64: "bla"
    } }}
)

如您所见,我为国家/地区使用手写的ID ...我可以在国家/地区之前进行查找查询,但是我们可以在此处使用填充吗?

我在邮递员那里得到了这个

enter image description here

预先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果类型为ObjectId,则它不能具有photos字段,因为它只是一个_id。它是对另一个集合的引用。

评论后更新的答案:

执行IMO的最佳方法是创建一个Photo模型,该模型将具有文件路径和国家/地区的_id。用户模型将仅存储照片[_id]的列表。

UserSchema:

{
   .....
   photos : [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Photo'
    }],
   .....
}

PhotoSchema:

{
    country : {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Country'
    },
    path : String
}

然后,通过填充照片并在每张照片中填充国家/地区,以此方式查询您的用户:

UserModel
        .find(conditions)
        .populate({ 
             path: 'photos',
             model: 'Photo'
             populate: {
                 path: 'country',
                 model: 'Country'
            } 
         })
         .lean() // Faster and lighter for read-only, simply returns an object

因此,您应该获得一个这样的User对象:

{
    .....
    name : "John",
    photos : [{
         country : {
              name : "Country 1",
              code : "C1" // or whatever field you have in your Country model
         },
         path: "path/to/photo1.jpg"
    },
    {
         country : {
              name : "Country 2",
              code : "C2"
         },
         path: "path/to/photo2.jpg"
    }]
    .....
}