Encountering a mongoose error when attempting to use the push()

var mongoose = require('mongoose'), 
    Schema = mongoose.Schema, 
    ObjectId = Schema.ObjectId;

var SongSchema = new Schema({
    name: {type: String, default: 'songname'},
    link: {type: String, default: './data/train.mp3'}, 
    date: {type: Date, default: Date.now()},
    position: {type: Number, default: 0},
    weekOnChart: {type: Number, default: 0},
    listend: {type: Number, default: 0}
});
module.exports = mongoose.model('Song', SongSchema);

album.js:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    SongSchema = require('mongoose').model('Song'),
    ObjectId = Schema.ObjectId;

var AlbumSchema = new Schema({
    name: {type: String, default: 'songname'},
    thumbnail: {type:String, default: './images/U1.jpg'},
    date: {type: Date, default: Date.now()},
    songs: [SongSchema]
});

app.js:

require('./models/users');
require('./models/songs');
require('./models/albums');

var User = db.model('User');
var Song = db.model('Song');
var Album = db.model('Album');

var song = new Song();
song.save(function( err ){
    if(err) { throw err; }
    console.log("song saved");
});

var album = new Album();
album.songs.push(song);

album.save(function( err ){
    if(err) { throw err; }
    console.log("save album");
});

Encountering an error

Cannot call method 'call' of undefined
when using album.songs.push(song);.

Please assist in resolving this issue. How can I effectively store multiple songs in an album?

Answer №1

You may have mixed up the concepts of model and schema.

Within the file albums.js,

var mongoose = require('mongoose'),
Schema = mongoose.Schema, 
SongSchema = require('mongoose').model('Song'), // The correct usage here should be a schema instead of a model
ObjectId = Schema.ObjectId;

One way to resolve this issue is to export SongSchema in songs.js, then import it into albums.js

Inside songs.js:

mongoose.model('Song', SongSchema); // This line registers the model
module.exports = SongSchema; // Export the schema instead of the model 

In albums.js

SongSchema = require('./songs');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve the `response.statusCode` while using piping in NodeJS Request?

Hey everyone, I could really use some help here. How can I properly log the status code using response.statusCode while using piping? var express = require('express'); var path = require('path'); var request = require('request&apo ...

Creating a user-friendly form with validation in a Vue application using Vuetify.js

I am in the process of incorporating a contact form with basic validation on a Vue.js website using an example from Vuetify.js. Being new to this, I'm unsure about how to implement it within a Vue component. My goal is to have simple client-side form ...

Having trouble setting the CSS width to 100%

Is there a way to assert the CSS width of an element in NightwatchJS to be 100% without hard-coding the value? Currently, when I attempt to do so, it fails and reports that the width is 196px. The specific error message is as follows: Testing if element ...

Turn off the scrolling bars and only allow scrolling using the mouse wheel or touch scrolling

Is there a way to only enable scrolling through a webpage using the mouse wheel or touch scrolling on mobile devices, while disabling browser scroll bars? This would allow users to navigate up and down through div elements. Here is the concept: HTML: &l ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...

React JS - Building a dynamic multi-tiered dropdown navigation system

Link to view the illustrative example: here. Could anyone advise on a solution for ensuring only one submenu is open at a time? For instance, when "menu 3" is opened, I would like "menu 2" to be automatically closed. ...

What is the best way to generate all possible combinations between two arrays of objects?

I am faced with the challenge of combining two arrays of objects, named origin and destination, to generate a final array that contains all possible combinations from the two arrays. For instance: origin = [ { id: 1, regionName: "Africa North&q ...

Display the page for 10 seconds continuously in a loop

I am currently developing a Node JS guessing game where data is collected on the back-end and sent to the front-end to start the game. The data consists of 10 levels, allowing the game to operate on a single page. Each level lasts for 10 seconds. Once the ...

Failed to cast value "some_id" to ObjectId for the field "_id" in the "Category" model

Encountering an issue while using findOne from Mongoose version 5.9.12. The error I received is shown here. I also encountered another error which can be viewed here. Here is my code: [code][2] You can find the screenshot of the error here. Additionally ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

Monitor the DOM for visibility changes in Selenium WebDriver and PjantomJS before proceeding

I am currently creating automated test scripts using selenium-webdriver, phantomJS, and mocha. The script file I'm working with is a JavaScript file. My goal is to wait until an element (<a>) is fully visible before clicking on it. Let me pro ...

How to filter an array in Angular 4 without the need for creating a new array and then displaying the filtered results within the same

In my collection of students, I have their names paired with their academic outcomes. studentResults = [ {name: 'Adam', result : 'Passed'}, {name: 'Alan', result : 'Failed'}, {name : 'Sandy', result : &ap ...

Develop a novel function

I am working on a new Order page where users can select a category, then a service, and fill out the quantity field for their order. I have an idea to create a function using @if and @else statements. In this function, I want to display the quantity fiel ...

How can you use JQuery to assign a single function as an onClick handler for multiple radio buttons?

I have a custom function named handleOnClickRadio(i, j);, and multiple radio buttons with the IDs in the format of id="something-radio[i][j]". These radio buttons are all contained within a table labeled "bigtable". Is there a way to link the function han ...

Error: The jQuery Class is returning an undefined value

I have been working on creating a basic AJAX request class in jQuery. However, I've encountered an issue with the 'process' function where I can get the response from the variable 'response'. When I return 'response', it ...

Customizing Geonames JSON Ajax Request

Having found the code I needed from a sample website, I am now seeking help to customize it to only display results from the USA. This is the current code snippet: $(function() { function log( message ) { $( "<div>" ).text( message ).pr ...

Exploring layered data through specific properties

Imagine a scenario where I have an array filled with data. Each element in this array is an object that could contain: an id some additional data a property (let's name it sub) which may hold an array of objects with the same properties (including t ...

Angular 5: There was an issue with the property not defined for lowercase conversion

I keep encountering this error whenever I attempt to filter a column of a table. The data is retrieved from a FireStore cloud collection and the 'auteur' field is defined in each document. Here is how my component looks: import { Component, OnI ...

What could be the reason for my mongoose model failing to save in mongodb?

I am experiencing an issue with my simple Post model and route for creating posts. After submitting a new post using Postman, the request hangs for a moment before returning an error in JSON format. The model data is never saved successfully. Below is the ...

Converting counterup2 to pure vanilla JavaScript: step-by-step guide

Is there a way to convert the counterUp2 jQuery code to vanilla JavaScript? const counters = document.querySelectorAll('.counter'); function count(element) { let currentValue = 0; const targetValue = parseInt(element.innerText); let interv ...