/    Sign up×
Community /Pin to ProfileBookmark

Pushing Mongoose documents to another document as array elements

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?

to post a comment

1 Comments(s)

Copy linkTweet thisAlerts:
@shakozzzauthorJun 07.2020 — A solution to this issue can be found [here](https://www.freecodecamp.org/forum/t/pushing-mongoose-documents-to-another-document-as-array-elements/400067/3).
×

Success!

Help @shakozzz spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...