Justin
Justin

Reputation: 33

Append to array nodejs mongodb

I am trying to append a string to an array that will be used to identify a user in multiple chatrooms. I have tried and can not get this to work. The log does not put out anything but:

[]

            if (req.body.method == "setid") {
            if(req.locals.user.chatid == null){
                req.locals.user.chatid = {};
            }

            app.model.User.update(
               { _id: req.locals.user._id },
               { $addToSet: { chatid: [{mid: req.body.value}]}  } 
            );
        } else if (req.body.method == "checkid" && req.body.value) {
            app.model.User.find({
                "chatid": req.body.value
            }, function(err, FoundUser) {
                if (err || !FoundUser) {
                    res.end("ERROR");
                } else {
                    console.log(FoundUser);
                    res.end(FoundUser[0].displayName);
                }
            });
        }

Mongo Structure

{
    email: { type: String, index: { unique: true }, required: true },
    password: { type: String },
    changeName: {type: Boolean},
    displayName: { type: String, index: { unique: true }, required: true },
    avatar: { type: String, default: '/assets/anon.png' },
    permissions: {
        chat: { type: Boolean, default: true },
        admin: { type: Boolean, default: false }
    },
    online: { type: Boolean, default: true },
    channel: { type: Types.ObjectId, ref: 'Channel', default: null }, //users channel
    banned: { type: Boolean, default: false },
    banend: {type:String, default: ''},
    subs: [{ type: Types.ObjectId, ref: 'User' }],
    about: { type: String },
    temporary: {type: Boolean, default: false},
    chatid:[{mid: {type:String}}]
}

Upvotes: 2

Views: 1561

Answers (1)

Ankit Gomkale
Ankit Gomkale

Reputation: 724

Let's focus only on below snippet of code:

 app.model.User.update(
               { _id: req.locals.user._id },
               { $addToSet: { chatid: [{mid: req.body.value}]}  } 
            );

First, please verify whether you are getting a user in this query or not. Maybe, you are not getting the user at the first place and hence update won't work. Moreover, you will not get any error in this scenario.

Secondly, if you are getting the user then update your $addToSet query as: { $addToSet: { chatid: {mid: req.body.value}}}. These square brackets might cause an issue here.

Your query seems fine to me, which makes me doubt the parameters you are passing. Make sure that req.body.value is not null or undefined. In that case, the update won't happen and you will not get any error also!

Upvotes: 1

Related Questions