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

leveraging npm packages in Vue single page applications

I recently developed a Vue.js application using vue-loader and now I am trying to integrate an npm package that I have installed. Here is the code snippet: var x = require('package-name') Vue.use(x) However, I encountered the following ...

How to display two elements side by side within a div using React

I have an array that looks like this: const arr = [1,2,3,4,5,6,7,8,9,10] I am looking to display the elements in pairs per line within two-dimensional divs. Here is what I have in mind: This represents the main React element: render() { return <di ...

JavaScript Tutorial: Extracting the text content of a drop event

Curious about extracting the text value from a drop event, I set out to find an answer. To my surprise, I discovered that it's not as straightforward as I thought. Check out the demo below: <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

What steps should I follow to generate a table using Ajax and Javascript when a button is clicked?

After spending hours following various tutorials and exploring previously asked questions, I am struggling to make this work. My HTML page looks like this: <!DOCTYPE html> <html> <head> <link type="text/css" rel="styleshee ...

Achieving unique proportions with HTML5 video resizing

On my page, I plan to showcase a video specifically for desktop browsers. I have devised some code to determine whether the video is in landscape or portrait orientation. The challenge lies in deciding what to do based on this orientation: If the video is ...

Using JavaScript and Ruby on Rails to dynamically modify URL query parameters based on a dropdown form

I need help updating a URL based on dropdown selection. I want the query to be dynamic, and here is my current code snippet: <select id="mySchool" onchange="this.form.submit()"> <% @schools.each do |school| %> <option value="< ...

Issue with dynamically filling a form field using ValidityState

I have been utilizing the ValidityState interface for client-side form validation, but I've encountered an issue. Whenever my form is populated programmatically, such as after making a call to a third-party API, the tooLong state always returns false, ...

Customizing the `toString()` method in Node.js exports

I'm having trouble overriding a toString() method in my code. I've already checked here and here, but haven't been able to solve the issue. This is what my code looks like: var Foo = function(arg) { // some code here... return fun ...

What is the best way to integrate node.js with HTML?

I am currently utilizing node.js to interact with an API on the IBM Cloud platform. I have successfully accessed the response in my code, but now I need to pass this data to an HTML page using "res.send". How can I achieve this? Below is the Node.js code ...

Transmitting a multidimensional array in JavaScript to an AjaxPro method on a front-end webpage: A step-by-step guide

Imagine a scenario where I have a C# method that requires an array parameter: [AjaxPro.AjaxMethod] public int Test3(string[,] array) { return array.Length; } Next, I define a multidimensional array on the front page using JavaScript: var array = ...

Toggle visibility of table row upon user click (HTML/JQuery)

Having an issue with showing or hiding table rows using jQuery. I would like it so that when a user clicks on a table row with id="jobtitle", the corresponding tr with class="texter" will either show up or hide if it is already displayed. This is my curre ...

Properly specifying the data type for a generic type variable within a function in TypeScript

As I work on my express project, I am currently coding a function called route. const morph = (params: Function[]) => (req: Request) => params.map(f => f(req)) const applyTransformers = (transformers: Function[]) => (response: any) => { ...

Tips for invoking a function from a JavaScript file within an Angular component

This particular query remains unanswered and pertains to AngularJS. I am seeking a solution specifically for Angular, as none of the existing answers online seem to be effective in my case. Here is an outline of my code: Columns.js export class Columns { ...

Could someone assist me in crafting a C# mongo query that mirrors the functionality of an SQL query?

MongoDB Error: Unsupported filter: ({document}{FILEDATE} > {document}{SPLITDATE}). Query in SQL: SELECT * FROM CURRENT AS C WHERE C.FILEDATE > C.SPLITDATE C# code snippet: db.GetCollection<CollectionName>().AsQueryable() .Where(a => a. ...

Error Encountered with Google Authentication in Localhost:3001 - Warning of 'Blocked Access'

Encountering a Next-auth Google authentication issue on my localhost development setup. Admin side (localhost:3000) and client side (localhost:3001) of e-commerce website are separate instances. Error message "access blocked" when trying Google authentica ...

Converting SQL code into Knex syntax

I am currently utilizing knex and objection to develop an API. My goal is to convert the following SQL code into knex without relying on raw so that I can retrieve all posts linked to a list of groups and other users. The information is stored in 4 diffe ...

Exploring touch interactions using D3.js and TUIO

I'm currently facing a challenge with implementing multi-touch functionality and the d3.slider in my D3 Map. You can see the current state of my project in this video. With the d3 slider, I can spawn points and navigate around the map using touch even ...

What is the process for extracting a cookie from response headers using AngularJS?

On my Node server, I have set a cookie using the following code: res.cookie('userValidation','true',{httpOnly: false, secure: false }); Now, I am trying to access this cookie in AngularJS. https://i.sstatic.net/DWTT5.jpg Does anyone ...

Should data be stored on the server, in a database, or as JSON files?

My application requires the storage of several basic objects that are subject to change, and it is essential for them to be persisted. Would it be more efficient to store the data in a database like MongoDB and retrieve it on startup, or simply save it to ...

Express - Enabling the addition of a trailing slash at the conclusion of a route

Even though routing in Express is usually simple, I'm facing an issue when trying to handle paths that have a trailing /. For instance, if I set up the following route: app.get('/about', (req,res) => res.render('about')); When ...