使用push()时出现mongoose错误

4
-- express示例 
|---- app.js 
|---- models 
|-------- songs.js 
|-------- albums.js 
|---- 其他的expressjs文件 

songs.js:

在这个文件中,我们定义了一个名为“songs”的模型。该模型具有以下属性:标题、艺术家和年份。我们还设置了一些方法来操作模型数据,例如获取所有歌曲和添加新歌曲。
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");
});

当我使用代码album.songs.push(song);时,我会遇到以下错误:

无法调用未定义的方法“call”。

请帮助我解决这个问题。如果我想在一个专辑中存储多首歌曲,应该怎么做?
1个回答

7
你混淆了modelschema的概念。
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;

解决它的一种方法是尝试在 songs.js 中导出 SongSchema,然后在 albums.js 中引用它。

songs.js 中:

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

albums.js文件中。
SongSchema = require('./songs');

那么,解决这个问题的简单方法是在一个文件models.js中安装所有模式。 对吗? 你能告诉我如何按照你的方式导出Schema吗?因为我尝试在Google上查找答案,但我什么也没有,可能是我使用了错误的关键字。 - Huy Tran
正在运行。非常感谢qiao。请帮我在这里解决。 - Huy Tran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接