1

I have two tables in my MongoDB database.

1) User 2) Message

In my application, when a user creates a "message", I am attempting to insert the messages as an array to the User Table.

The Schemas defined for User and Messages are as shown below

Message Scheme

var schema = new Schema({
content: {type: String, required: true},
user: {type: Schema.Types.ObjectId, ref: 'User'}
});

User Schema

var schema = new Schema({
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    password: {type: String, required: true},
    email: {type: String, required: true, unique: true},
    messages: [{type: Schema.Types.ObjectId, ref: 'Message'}]
});

I have a post method defined as shown below:

router.post('/', function (req, res, next) {
var decoded = jwt.decode(req.query.token);
User.findById(decoded.user._id, function (err, user) {
    if (err) {
        return res.status(500).json({
            title: 'An error occurred',
            error: err
        });
    }
    var message = new Message({
        content: req.body.content,
        user: user._id
    });
    console.log("Message:"+ message);
    message.save(function (err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });
        }
        user.messages.push(result);
        user.save();
        console.log('Saved...'+user);

        res.status(201).json({
            message: 'Saved message',
            obj: result
        });
    });
  });
});

Here I first check if user exists and then insert the message sent into the "Message" table with userid reference and attempt to make a corresponding entry in the user table by pushing the Message into the column type that will accept messages as an array.

On running the application, in my console I can see the messages object attached to the user collection as shown below:

enter image description here

But when I check my database to see if the message is attached, it shows the message array as null:

enter image description here

Not sure where I am going wrong in attaching the array to the collection.

2 Answers 2

1

Make a minor change:

message.save(function (err, result) {
        // ... your other code 

        user.messages.push(result.id || result._id); // CHANGE THIS LINE
        user.save();
        console.log('Saved...'+user);

        res.status(201).json({
            message: 'Saved message',
            obj: result
        });

    });
Sign up to request clarification or add additional context in comments.

3 Comments

Hey Zeeshan , I tried your suggestion but it doesnt work. The message array in the User Collection is still empty
alright, what I suggested works on the version i have on my local machine, it means your problem was related to unstable/newer version but happy that your issue is resolved :)
Thanks a lot for your inputs Zeeshan .
0

I finally got it to work by updating the Schema for the User collection .

My Updated Schema is -

var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
messages: [{type: Schema.Types.ObjectId, ref: 'Message'}]

},

{ usePushEach: true }, // ADDED THIS
);

Reference :

https://github.com/Automattic/mongoose/issues/5574#issuecomment-332290518 https://github.com/Automattic/mongoose/issues/5924

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.