These are chat archives for Automattic/mongoose

Jun 2017
Thomas Havlik
Jun 16 2017 01:06
Is there a way to easily replace all instances of one ObjectID with another, or at least tell mongo that all queries for one id should be redirected to another object?
Alvaro Almendros Gala
Jun 16 2017 04:15

I’m having trouble finding info about how to decrease a field with a percentage of itself

    { '': { $gt: 0 } },
    { $inc: { '': -Math.floor($ * 0.05)} }

As you can see I found how to do the negative increment…but how do I work with the original quantity I want to decrease? :)

I want to decrease a 5% of the elo of every guild member once a day, by cron
Alvaro Almendros Gala
Jun 16 2017 04:25
I want it to be calculated directly if I could. I may try with find() then forEach -> update(), but having updateMany() and $inc, I want to learn if there is a way to use the original value of every item :)
Alvaro Almendros Gala
Jun 16 2017 04:37

…I mean, maybe I should use something like this:

Guildmembers.find({ '': { $gt: 0 } })
  .then((guildmembers) => {
    guildmembers.forEach((member) => {
      let amount = Math.floor( * 0.05)
      Guildmembers.update({ '_id': member._id },
        { $inc: { '': -amount } })

But I would like to know if there is a most direct way to do it with updateMany() :)

Teogenes Moura
Jun 16 2017 17:16
Hi, how are you?
First of all, I'm new to mongoose and Gitter, so please forgive me if I'm posting on the wrong place
I have two models
let electionSchema = new Schema({
electionID : Number,
    name       : String,
    voters       : [{    type: Schema.Types.ObjectId, ref: 'Voter'}],
    votechain        : { type: Schema.Types.ObjectId, ref: 'Votechain' }
var voterSchema = new Schema({ 
    name: {
        type: String,
        required: true
    isCandidate:  Boolean, 
    createdAt: { type:Date, default: }
I'm trying to add a Voter to the Schema election using this piece of code:
    let election = Election.findOne({ 'name' : req.body.electionName }, function(err, election ){
        if(err) return err;
        return election;
    let voter      = Voter.findOne({ 'name' : req.body.voterName }, function(err, voter) {
        if(err) return err;
        return voter;
    election.update({ $push: { 'voters': voter }});
and I'm getting this error:
CastError: Cast to ObjectId failed for value "[object Object]" at path "voters"
Teogenes Moura
Jun 16 2017 17:21
and I can't see why that is happening
is there a better approach to this problem than the one I'm trying?
Jun 16 2017 18:21
@teogenesmoura have you checked the values of election and voter, are those queries synchronous to write them one after another ? Election.findOne and Voter.findOne guarantees to find one or you should write a check ?