Home > Net >  Mongoose auto-increment fails because of a cast error
Mongoose auto-increment fails because of a cast error

Time:12-21

I am trying to increment a simple number field, but it is telling me it is failing to to a casting error.

CastError: Cast to Number failed for value "{ '$inc': 1 }" (type Object) at path "times_dealt"

Says it's an object?

This is my schema for Answer

const answerSchema = new mongoose.Schema({
    body: {
        type: String,
        trim: true,
        required: true,
    },

    times_dealt: {
        type: Number,
        required: true,
    },
    times_picked: {
        type: Number,
        required: true,
    },
    times_won: {
        type: Number,
        required: true,
    },
}, {
    timestamps: true,
});

module.exports = { answerSchema };

This is my route for me the admin to add new answers (it's a game so only I can add them, that why the auth. Figured I'll include the complete code.)

router.post("/answers", async(req, res) => {
    try {
        const isMatch = await bcrypt.compare(
            req.body.password,
            process.env.ADMIN_PASSWORD
        );

        if (isMatch) {
            const answer = new Answer({
                body: req.body.answer.trim(),
                times_dealt: 0,
                times_picked: 0,
                times_won: 0,
            });
            await answer.save();

            res.status(201).send(answer);
        }
        res.status(401).send();
    } catch (e) {
        console.log("failed to save", e);
        res.status(400).send(e);
    }
});

Then whenever a card is dealt, I want to increase the count for times_dealt, and this is when I get the error. This is how I do it:

async function getOneAnswerCard(room) {
    if (room.unused_answer_cards.length !== 0) {
        // We pick a random answer's ID from our array of unused answers
        const randomAnswerID = getRandomElement(room.unused_answer_cards);

        // We get that answer's full object from our DB
        const newAnswer = await Answer.findById(randomAnswerID);

        // const newAnswer = await Answer.findByIdAndUpdate(randomAnswerID, {
        //     times_dealt: { $inc: 1 },
        // });
        await Answer.findByIdAndUpdate(randomAnswerID, {
            times_dealt: { $inc: 1 },
        });

        // We remove it from the unused cards array
        room.unused_answer_cards = room.unused_answer_cards.filter(
            (answerID) => answerID !== randomAnswerID
        );

        // We add it to the dealt cards array
        room.dealt_answer_cards.push(randomAnswerID);

        // We serialize the answer (we don't want the user to get info on our answer stats)
        const serializedAnswer = { _id: newAnswer._id, body: newAnswer.body };

        return serializedAnswer;
    }
}

Just getting the answer by itself is no issue. Getting a random ID and fetching an answer object works just fine. It's only when I've added the increment functionality that it started crashing.

CodePudding user response:

I think you're using $inc with a wrong syntax. Try this:

await Answer.findByIdAndUpdate(randomAnswerID, {
  { $inc: { times_dealt: 1 } },
});
  • Related