Home > Enterprise >  Problems with drawing a random winning entry from a MongoDB database (with Mongoose & NodeJS)
Problems with drawing a random winning entry from a MongoDB database (with Mongoose & NodeJS)

Time:02-20

I'm struggling to get the following code to work, using MongoDB, Mongoose and NodeJS. I have two schemas, one to save unique user profiles, the other to save their entries (such that they can enter multiple times). The entries all work (not shown here), it is just the selection of the winner that doesn't. It should randomly select one entry from the collection, find their unique profile and set the 'won' Boolean to true and delete all the entries in the collection. It currently does none of those things (but I've checked the routing all works fine and the const is triggered), so some assistance would be greatly appreciated. I've tried various methods, but found no clear guidance anywhere. Thanks.

The controller

const { Enter } = require('../models/user_entry');
const { UserProfile } = require("../models/User_Profile");

const drawWinner = async (req, res) => {
  const winner = Enter.aggregate([{ $sample: { size: 1 } }]); 
  const users_profile = await UserProfile.findOne({ handle: winner.user });
  users_profile,{"$set":{"won":true}}; 
  await users_profile.save();
  Enter.deleteMany({  });
};

module.exports = {
  drawWinner
}; 

The models:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Entry Schema
const EntrySchema = new Schema({
  user: {
    type: String,
    required: true,
  },
});

const Enter = mongoose.model("entries", EntrySchema);

module.exports = { Enter };
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Profile Schema
const UserProfileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "user",
  },
  handle: {
    type: String,
    required: true,
    trim: true,
    unique: true,
  },
  won: {
    type: Boolean,
    default: false,
  },
});

const UserProfile = mongoose.model("profile", UserProfileSchema);

module.exports = { UserProfile }; 

CodePudding user response:

You are missing await while aggregating the database

const winner = await Enter.aggregate([{ $sample: { size: 1 } }]); 

You might also want do console.log(winner) in order to check if are getting any data back from database.

EDIT

As per your comment you are getting winner.user value

The way you are using updating user is weird, try this instead

let updated_user = await UserProfile.findOneAndUpdate({ handle: winner.user }, { won: true },{ new: true });

You can delete these 3 lines

const users_profile = await UserProfile.findOne({ handle: winner.user });
users_profile,{"$set":{"won":true}}; 
await users_profile.save();

Also while deleting the entries use await Enter.deleteMany({});

You also need to send some response back res.send() otherwise server will hang.

  • Related