【问题标题】:mongoose error when use push()使用 push() 时出现猫鼬错误
【发布时间】:2012-02-02 22:37:51
【问题描述】:
-- express_example |---- app.js |---- 型号 |-------- 歌曲.js |-------- 专辑.js |---- 和 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);

专辑.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); 时,我得到了错误:

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

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

【问题讨论】:

    标签: javascript mongodb express mongoose nosql


    【解决方案1】:

    你混淆了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 中。那正确吗?你能告诉我如何以你的方式导出架构,因为我试图在谷歌上找到答案,但我什么都没有,也许我使用了错误的关键字
    • 它正在运行。非常感谢qiao..请在HERE中帮我解决
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2021-09-25
    • 2013-05-06
    • 2021-03-09
    相关资源
    最近更新 更多