简体   繁体   中英

Mongodb (mongoose) I can't remove sub element from array

I'm creating a league of legends tournament website for a friend, and for each tournament (stored in a database with mongodb) has a list of "premades" of players that want to play the tournament.

I'm using the mongoose module on node.js to manage my database

Here is my model:

const tournamentSchema = mongoose.Schema({
    name: {
        type:String,
        required:true,
        trim: true
    },
    beginningDate: Date,
    endingDate: Date,
    creatorName: {
        type:String,
        required:true,
        lowercase: true,
        trim: true
    },
    maxPlayers:Number,
    maxPlayersPerTeam:Number,
    playersList:Array,
    waitingPlayers:Array,
    needLoggin:{
        type:Boolean,
        default:false
    },
    description:String
});

For exemple, "playersList" will be:

playersList:[
{
  name:"group1",
  players:[
    {
      name:"player1",
      elo:"rank on the game"
    },
    {
      name:"player2",
      elo:"rank on the game"
    }
  ]
},
{
  name:"group2",
  players:[
    {
      name:"player3",
      elo:"rank on the game"
    },
    {
      name:"player4",
      elo:"rank on the game"
    }
  ]
}

]

And I'm trying to find how to remove the

{
  name:"player4",
  elo:"rank on the game"
}

in the group 2 for exemple. I tried to use splice() like if it was a normal array, it updated the object but did nothing in the database. I also tried the tournament.update and it returned an error and I couldn't see what was my mistake...

var collection = Rtournament.players;
Rtournament.updateOne({'players.players.name':collection[i].players[j].name},{$pull:{'players.$.players':{'name':name}}},()=>{});

So I would like to know a simple way to remove it (as I'm sure my code was really wrong)

Thanks a lot to help me and sorry for my awful english

You can use this to pull the players according to your group. You will have to pass group name and players name.

db.collection.update({
  $and: [
    {
      name: "group2"
    },
    {
      "players.name": "player4"
    }
  ]
},
{
  $pull: {
    players: {
      name: "player4"
    }
  }
})

Mongo Playground: https://mongoplayground.net/p/HEusd_OBO1F

Here is standalone script to test, let me know if it works Start the mongodb in shell then run node repro.js in terminal

const mongoose = require('mongoose');

const tournamentSchema = mongoose.Schema({
    name: {
        type:String,
        required:true,
        trim: true
    },
    beginningDate: Date,
    endingDate: Date,
    creatorName: {
        type:String,
        lowercase: true,
        trim: true
    },
    maxPlayers:Number,
    maxPlayersPerTeam:Number,
    players:Array,
    waitingPlayers:Array,
    needLoggin:{
        type:Boolean,
        default:false
    },
    description:String
});


run().catch((err) => console.log(err));

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    await mongoose.connection.dropDatabase();

    const TournamentModel = mongoose.model('tournament', tournamentSchema);
    await TournamentModel.insertMany([
        {
          name:"group1",
          players:[
            {
              name:"player1",
              elo:"rank on the game"
            },
            {
              name:"player2",
              elo:"rank on the game"
            }
          ]
        },
        {
          name:"group2",
          players:[
            {
              name:"player3",
              elo:"rank on the game"
            },
            {
              name:"player4",
              elo:"rank on the game"
            }
          ]
        }
        
        ])
    await TournamentModel.updateOne({
        $and: [
          {
            name: "group2"
          },
          {
            "players.name": "player4"
          }
        ]
      },
      {
        $pull: {
          players: {
            name: "player4"
          }
        }
     });
    const result = await TournamentModel.find({}).lean()
    console.log(JSON.stringify(result), 'result')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM