0

I trying to make Account Schema with achievements key property as array of ref objectsIDs and another properties, but can't figure out how to do this. When pushing data only ref objectId is pushed without another properties.

Is there better way than just storing in one array object Refs and in another another properties?

  achievements: [{achievement: {type: Schema.Types.ObjectId, ref: 'Achievement'}}, {
        claimed: {
            type: Boolean,
            default: false
        }
    }, {
        isDone:
            {type: Boolean, default: false}
    }, {
        current:
            {type: Number, default: 0}
    }],
AccountSchema.statics.addAllExistingAchievements = (account: any) => {
    return new Promise((resolve, reject) => {
            return Achievement.find().exec().then((achievements: any) => {
                achievements.map((achievement: any, index: number) => {
                    account.achievements.push({achievement: achievement}, {claimed: false}, {isDone: false}, {current: 0})
                    if (achievements.length - 1 === index) {
                        account.save();
                    }
                })

                resolve({success: true});
            }).catch((e: any) => reject(e));
        }
    )
}
  • why do you use `ref` in your model? MongoDB has the join-like $lookup aggregation operator. Mongoose has alternative called populate(), which lets you `ref` documents in other collections.Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). but you use ref for a model with itself – Mohammad Yaser Ahmadi Jan 11 '21 at 08:24
  • @MohammadYaserAhmadi As u can see I use refs. I tried to have array with ref and additional data to prevent creating two arrays that will be merged on front-end, but don't have any clue how to do that. – Jakub Dobrzeniecki Jan 11 '21 at 14:26
  • is your problem solved? if your answer is no, please added controller, don't need to `statics.addAllExistingAchievements` function, if you think need it can you explain it? – Mohammad Yaser Ahmadi Jan 12 '21 at 14:40
  • I made workaround two fields one containg ref and another one with user data(to check if he done achievement, claimed prize and so on). Function `statics.addAllExistingAchievements` is must have from my concern. As this is part of account creating path and if user account don't get possible achievements that he can have there will be error in the game. I made Achievement collection to store all achievements in the game with things to do ,desc and rewards and this is stored also in user account as ref, but game need to know if user claimed prizes and if not what progress is. – Jakub Dobrzeniecki Jan 13 '21 at 12:53

0 Answers0