我收到以下错误,使用快递在Node.js中执行应用程序。 我正在使用Mongoose进行数据库操作,我已经详细介绍了我的设计
Party.js
var mongoose = require("mongoose");
var partySchema = new mongoose.Schema({
partyName: String,
songs: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Song"
}
]
});
module.exports = mongoose.model("Party", partySchema);
Song.js
var mongoose = require("mongoose");
var songsSchema = new mongoose.Schema({
videoId: String,
videoName: String
});
module.exports = mongoose.model("Song", songsSchema);
我的App.js
app.post("/search/addSong", function(req, res) {
Party.find({partyName:"hello"},function(err,party){
if(err){
console.log("Failed in find");
} else {
console.log(party);
// console.log(typeof(req.body.videoId));
var videoId = req.body.videoId;
var newSong = [ {
videoId:req.body.videoId,
videoName:req.body.videoName
}
];
Song.create(newSong, function(err, createdSong){
if(err){
console.log("Error creating a new party");
} else {
console.log(createdSong);
party.songs.push(createdSong);// ERROR ON THIS LINE
party.save();
res.redirect("/search");
}
});
}
});
res.render("addSong");
});
我可以单独创建Party和Song的集合对象,当我将歌曲添加到派对队列时,我收到以下错误:
TypeError: Cannot read property 'push' of undefined
任何人都可以让我知道我在这里失踪了什么.. !!
提前致谢。!!
答案 0 :(得分:0)
find返回一个在数组中转换的游标。如果您期望单个文档,请调用findOne。
app.post("/search/addSong", function(req, res) {
Party.findOne({partyName:"hello"},function(err,party){
if(err){
console.log("Failed in find");
} else {
console.log(party);
// console.log(typeof(req.body.videoId));
var videoId = req.body.videoId;
var newSong = [ {
videoId:req.body.videoId,
videoName:req.body.videoName
}
];
Song.create(newSong, function(err, createdSong){
if(err){
console.log("Error creating a new party");
} else {
console.log(createdSong);
party.songs.push(createdSong);// ERROR ON THIS LINE
party.save(function(err){
res.redirect("/search");
});
}
});
}
});
res.render("addSong");
});
还将重定向放在save的回调中,它将确保仅在保存完成时调用重定向,否则它将重定向而不保存,从而提供javascript的异步性质。