Home > database >  $pull works in mongosh but not in mongoose
$pull works in mongosh but not in mongoose

Time:12-15

User schema:

const UserSchema = new mongoose.Schema(
  {
    contacts: {
      type: Array,
      default: [],
    }
  }

);

module.exports = mongoose.model("User", UserSchema);

Data in mongodb

{
    "_id": ObjectId("6171fbcd85279d467c9b5be9"),
    "contacts":[
        {
            "_id": ObjectId("61a7b499455e053ae4e4baeb"),
            "firstName":"Johnny",
            "lastName":"Cool",
            "occupation":"Programmer",
            "company":"Cool Comp."
        },

        {
            "_id":ObjectId("61a7b4be455e053ae4e4baec"),
            "firstName":"Evan",
            "lastName":"Evernost",
            "occupation":"Manager",
            "company":"Best Comp."
        }
    ]
}

This delete query works in mongosh and the contact is removed from the database

db.users.updateOne(
  {'_id':ObjectId('6171fbcd85279d467c9b5be9')},
    {$pull: 
      {'contacts':
        {'_id': ObjectId('61a7b499455e053ae4e4baeb')}
      }
    }
)

The resulting data looks like and should look like this:

{
    "_id": ObjectId("6171fbcd85279d467c9b5be9"),
    "contacts":[
        {
            "_id":ObjectId("61a7b4be455e053ae4e4baec"),
            "firstName":"Evan",
            "lastName":"Evernost",
            "occupation":"Manager",
            "company":"Best Comp."
        }
    ]
}

However, when I run this query in using npm's mongoose library the command "succeeds" however the contact isn't removed from the database.

User.updateOne(
  {'_id': mongoose.types.ObjectId('6171fbcd85279d467c9b5be9')},
    {$pull: 
      {'contacts':
        {'_id': mongoose.types.ObjectId('61a7b499455e053ae4e4baeb')}
      }
    }
)

The resulting data looks like this

{
    "_id": ObjectId("6171fbcd85279d467c9b5be9"),
    "contacts":[
        {
            "_id": ObjectId("61a7b499455e053ae4e4baeb"),
            "firstName":"Johnny",
            "lastName":"Cool",
            "occupation":"Programmer",
            "company":"Cool Comp."
        },

        {
            "_id":ObjectId("61a7b4be455e053ae4e4baec"),
            "firstName":"Evan",
            "lastName":"Evernost",
            "occupation":"Manager",
            "company":"Best Comp."
        }
    ]
}

Instead of this:

{
    "_id": ObjectId("6171fbcd85279d467c9b5be9"),
    "contacts":[
        {
            "_id":ObjectId("61a7b4be455e053ae4e4baec"),
            "firstName":"Evan",
            "lastName":"Evernost",
            "occupation":"Manager",
            "company":"Best Comp."
        }
    ]
}

Not sure what the problem is.

CodePudding user response:

It is as simple as needing to add the await keyword since updateOne is an async function

await User.updateOne(
  {'_id': mongoose.types.ObjectId('6171fbcd85279d467c9b5be9')},
    {$pull: 
      {'contacts':
        {'_id': mongoose.types.ObjectId('61a7b499455e053ae4e4baeb')}
      }
    }
)
  • Related