Mongoose error when using push ()

  - express_example 
 | ---- app.js 
 | ---- models 
 | -------- songs.js 
 | -------- albums.js 
 | ---- and another files of expressjs 

songs.js:

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"); }); 

When I use the code album.songs.push(song); , I get an error:

Unable to call undefined `call method.

Please help me solve this problem. If I want to save many songs in an album, how do I do this?

+4
source share
1 answer

You are confused between model and schema

in albums.js ,

 var mongoose = require('mongoose'), Schema = mongoose.Schema, SongSchema = require('mongoose').model('Song'), // <<<<<<<<<< here should be a schema istead of a model ObjectId = Schema.ObjectId; 

one way to fix this is to try exporting SongSchema to songs.js and then request it to albums.js

in songs.js :

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

in albums.js

 SongSchema = require('./songs'); 
+6
source

Source: https://habr.com/ru/post/1389382/


All Articles