Reputation: 152
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:
But when I check my database to see if the message is attached, it shows the message array as null:
Not sure where I am going wrong in attaching the array to the collection.
Upvotes: 1
Views: 36
Reputation: 152
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
Upvotes: 0
Reputation: 8325
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
});
});
Upvotes: 1