Thursday, 3 October 2019

Set field in mongoose to array length

I have a Mongoose document:

var SkillSchema = new mongoose.Schema({
    skill: { type: String },
    tally: { type: Number, default: 0 },
    associatedUsers: [{ type : mongoose.Schema.Types.ObjectId, ref: 'User' }]
});

That I update as follows:

var query = {skill: req.body.skill};
var update = { $addToSet: { associatedUsers: req.params.id } };

var options = { upsert: true, new: true, setDefaultsOnInsert: true };

await skillSchema.findOneAndUpdate(query, update, options);

During this update, I would like to also update tally to be equal to the length of associatedUsers.

Ideally I want this to happen at the same time as updating the other fields (not in a subsequent update), either via a pre-hook or within findOneAndUpdate.

I've tried using a pre hook after schema definition:

SkillSchema.pre('findOneAndUpdate', async function(){
    console.log("counting associated users");
    this.tally = this.associatedUsers.length;
    next();
});

As well as using aggregate in my UPDATE route:

await skillSchema.aggregate([{ $project: { tally: { $size: "$associatedUsers" } } } ])

But I can't get either to work.

Does anyone have any suggestions for how I could achieve this?



from Set field in mongoose to array length

No comments:

Post a Comment