Hi everyone,
I have two models, user.model.js and bundle.model.js. Inside the user model, I have a bundles array where I’d like to add Bundle documents. Here’s how it looks:
user.model.js
"use strict";
const mongoose = require('mongoose');
// Define the user schema
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
bundles: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Bundle',
require: false,
}
]
});
UserSchema.set('versionKey', false);
// Export the User model
module.exports = mongoose.model('User', UserSchema);
bundle.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bundleSchema = new Schema({
remainingStories: { type: Number, required: true },
activationDate: { type: Date, required: true },
}, { timestamps: { createdAt: 'purchaseDate' } });
const Bundle = mongoose.model('Bundle', bundleSchema);
module.exports = Bundle;
In my users.js I have a route that I want to use to add new bundles to a user. The expected behavior is for the new bundle to be added to the user’s bundles array and also to the bundles collection in MongoDB. For some reason, however, no matter how many times I push() new bundles to the array, there’s only ever one bundle in there. Also, those bundles are never added to the bundles collection in MongoDB. Here’s the relevant code in users.js:
const router = require('express').Router();
const User = require('../models/user.model');
const Bundle = require('../models/bundle.model');
...
router.route('/add-bundle/:id/').post((req, res) => {
const remainingStories = Number(req.body.remainingStories);
const activationDate = eval(req.body.activationDate);
User.findById(
{ _id: req.params.id },
{ useFindAndModify: false })
.exec()
.then(user => {
const bundle = new Bundle({
remainingStories,
activationDate
});
console.log(bundle);
user.bundles.push(bundle);
// console.log(user);
res.status(200).json(user);
user.save(() => console.log('Save successful!'))
})
.catch(err => res.status(400).json('Error: ' + err));
});
Any hints?