我正在创建一个express.js应用程序,并用猫鼬制作了一个数据库以进行测试。数据库位于我导出到app.js文件的function seedDB()
内部。创建种子数据库没有错误,但是当我在该数据内部添加新的“审阅”时。即使我的猫鼬模型设置正确,也要说cannot read property "push" of undefined
。
我在mongoDB中有两个集合,分别称为“ tours”和“ reviews” 我尝试使用db.tours.find()在mongo shell中查找游览,然后发现我的“ review”(与review集合关联的数组)已正确设置。但是当我查找db.reviews.find()时。它也在那里,但是它的结果大约是我预期的x4。
我尝试检查是否只是忘记了括号,花括号,但我认为这不是问题。 我还尝试反复查看我的模型并再次更改,但是也没有问题
const tours = require("./models/tours");
const Review = require('./models/reviews');
let tourData = [{
image: "image.jpg",
place: "Place",
name: "name",
description: "this is a description",
price: 1234,
info: "this is a great tour"},
{
image: "image.jpg",
place: "Place",
name: "name",
description: "this is a description",
price: 1234,
info: "this is a great tour"},
{
image: "image.jpg",
place: "Place",
name: "name",
description: "this is a description",
price: 1234,
info: "this is a great tour"},
]
function seedDB(){
tours.deleteMany({}, (err)=>{
if(err){
console.log(err);
}
console.log("removed tours!");
//add a few tours
tourData.forEach(function(seeds){
tours.create(seeds, (err, data)=> {
if(err){
console.log(err)
} else {
console.log('added all tours!');
//create a comment
Review.create(
{
text: "this place is great! ",
author: "Arnold"
}, (err, comment)=> {
if(err){
console.log(err)
} else {
tours.reviews.push(comment); //why is this undefined? I set it up correctly
tours.save();
console.log("created new review")
}
});
}
});
});
});
};
module.exports = seedDB
直到console.log('added all tours!');
运行良好,但是当我放置Review.create()
时,它现在出现了错误,特别是tours.reviews.push(comment);
//tours.js model
const mongoose = require('mongoose');
var ToursSchema = new mongoose.Schema({
image: String,
place: String,
name: String,
description: String,
price: Number,
info: String,
creator: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
reviews:[
{
type: mongoose.Schema.Types.ObjectId,
ref: "Review"
}
]
});
let Tours = mongoose.model('Tour', ToursSchema);
module.exports = Tours;
reviews.js模型
const mongoose = require('mongoose');
var reviewSchema = mongoose.Schema({ //I also tried doing new Mongoose.Schema({
text: String,
author: String
});
module.exports = mongoose.model('Review', reviewSchema);
控制台中的预期结果应该是
removed tours!
added all tours!
added all tours!
added all tours!
created new review
created new review
created new review
,而mongo数据库中的实际结果是在array of reviews
内有一个tours collections
。
答案 0 :(得分:1)
多件事:
tours
是您的模型,而不是您的实例。您想加入一个或所有实例的审核,在您的情况下为data
。因此,根据您的情况,您可以执行类似data[0].reviews.push(comment)
的操作。由于tours
是小写字母,因此我可以看到您是如何混淆的,这使它看起来像是实例,而不是模型。
在data
之后的倒数第二个变量名是data2
:-P
考虑使用更易于阅读和维护async / await语法的方式替换您的回调
不直接要求您使用模型,而是注册模型并使用mongoose.model('tours')