我正在创建一个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()时。它也在那里,但是它有大约4倍的预期结果。
我尝试检查是否只是忘记了括号,花括号,但我认为这不是问题。
我也尝试反复查看我的模型并再次更改,但也没有问题
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
。 最佳答案
多项内容:tours
是您的模型,而不是您的实例。您想加入一个或所有实例的审核,在您的情况下为data
。因此,您可以执行data[0].reviews.push(comment)
之类的操作。由于tours
是小写字母,因此我可以看到您的想法如何混乱,这使其看起来像是实例,而不是模型。data
之后的第二个最差的变量名称是data2
:-P
考虑用更容易阅读和维护异步/等待语法替换回调
不直接需要您的模型,而是注册模型并使用mongoose.model('tours')