gpt4 book ai didi

javascript - 使用 push() 时出现 Mongoose 错误

转载 作者:可可西里 更新时间:2023-11-01 09:11:03 26 4
gpt4 key购买 nike

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

专辑.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]
});

应用程序.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); 时,出现错误:

Cannot call method 'call' of undefined`.

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

最佳答案

你混淆了 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');

关于javascript - 使用 push() 时出现 Mongoose 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8736836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com