1

Sorry if this is a repetitive one, I really couldn't solve it with any of the information provided here.

Basically I have this in my User.js mongoDB schema:

notifications: [{
        type: String,
        story: String,
        seen: Boolean,
        createdTime: Date,
        from: {
            name: String,
            username: String,
            id: mongoose.Schema.ObjectId
        }
    }]

After I query the user, this is what I do to push this object:

var notifObj = {

    type: notification.type,
    story: notification.story || ' ',
    seen: false,
    createdTime: new Date(),
    from: {
        name: notification.from.firstName + " " + notification.from.lastName,
        username: notification.from.username,
        id: notification.from._id
    }
};

into the mongoDB database:

user.notifications.push(notifObj);

User.update({
    _id: notification.to
}, user, function(err, data) {

    if (err) {

        deferred.reject({
            err: err
        });
    }

    //Tell sender everything went alrgiht
    deferred.resolve(data);
});

P.S.: I have deferred.resolve instead of res.end(), because I push notifications on some of the requests in a different controller, I don't have a separate route only for notifications. (e.g.: User has a new message, I send the message and push a notification too)

2
  • Are you sure it's saving as [object object], or is that just how it displays when you try to console.log the object? Try logging a property on the object that is a simple type, like notifObj.seen Commented Feb 18, 2015 at 21:45
  • 1
    Check the answer, you will not be sure whether to laugh or to facepalm... :/ Commented Feb 18, 2015 at 21:51

1 Answer 1

3

I found out why mongoDB was always converting my Object to String and giving me an ["object Object"] and the reason is very simple - NEVER use reserved/common words for object keys. MongoDB was interpreting my notification: {type: String, ...} as a field, which holds a String as value and not as a notification, which has type, seen and other properties. A quick fix to my User.js Schema is:

notifications: [{
        notifType: String,
        story: String,
        seen: Boolean,
        createdTime: Date,
        from: {
            name: String,
            username: String,
            id: mongoose.Schema.ObjectId
    }]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.