Idos
Idos

Reputation: 15310

NodeJS unable to addToSet in MongoDB

I want to update a field in my JSON which is an array with an element (simple, eh?).
I want to add userid to the reportedUsersIDs array.
The query I'm running (via POSTMAN):
http://localhost:3000/api/listing/myStreet/1/1/addReportedUser/564b343fbc2d4310156c6bf9/5671a8f694745bfce5bf6ecf

I checked both ID's exist in the DB and the listing itself exists as well (on street = myStreet, buildingNumber = 1, apartmentNumber = 1).
The code in routes.js is:

app.put('/api/listing/:street/:buildingNumber/:apartmentNumber/addReportedUser/:userid/:listingid', function (req, res) {

    var listingToUpdate = req.params.listingid;
    var idToAdd = req.params.userid;
    Listing.update({_id: ObjectId(listingToUpdate)},
        {$addToSet: {reportedUsersIDs: ObjectId(idToAdd)}}
        , function (err, listing) {
            if (err) {
                res.send("There was a problem adding the reportedUserID to the listing" + err);
            }
            else {
                console.log("Success adding reportedUserID to listing!");
                res.json(listing);
            }
        })
});

And it returns successful but the JSON remains unchanged.

Relevant data:

Schema of the listing I am trying to change:

var listingSchema = new Schema({
        street          : String,
        buildingNumber  : Number,
        apartmentNumber : Number,
        reportedUsersIDs: [String]
});

And my user schema:

var userSchema = new Schema({
    local            : {
        email        : String,
        password     : String
    },
    name             : String
});

Why is my JSON not being updated?

Upvotes: 3

Views: 1327

Answers (1)

robertklep
robertklep

Reputation: 203286

Since reportedUsersIDs is declared in your schema as an array of String, you should add them as strings too, instead of as ObjectId:

{ $addToSet : { reportedUsersIDs : idToAdd } }

Alternatively, you can change your schema so it's an array of ObjectId:

reportedUsersIDs : [ Schema.Types.ObjectId ]

Upvotes: 2

Related Questions