我用猫鼬写了2个模型。首先是用户,另一个是电影。我在下面写了这个模型。首先,我将所有用户保存在用户集合中。之后,我要将电影保存到电影收藏中。但是当我要定义我的导演字段时,出现错误“ ReferenceError:未定义导演”
const userSchema = new Schema({
imdbId: String,
name: String,
});
var User = mongoose.model('user', userSchema);
const movieSchema = new Schema({
imdbId: String,
title: String,
rank: Number,
year: Number,
stars:[{
type: Schema.Types.ObjectId,
ref: 'userSchema'
}],
director:{
type: Schema.Types.ObjectId,
ref: 'userSchema'
}
});
var Movie = mongoose.model('movie', movieSchema);
module.exports = {Movie, User}
这是我的功能:
async function findObjectIdByImdbId(str) {
const result = await User.findOne({ imdbId: str})
return result._id
}
async function insertMovieToDb (obj) {
var movie = new Movie ({
imdbId: obj.id,
title: obj.name,
rank: obj.rank,
rating: obj.rating,
year: obj.year,
director: await findObjectIdByImdbId(obj.director)
})
await movie.save(function(err) {
if (err) {console.log(err)
return
}})
}
insertJsonFileToDb().catch(console.log)
答案 0 :(得分:0)
将await findObjectIdByImdbId(obj.director)
从电影初始化中移出
例如
var directorObjId = await findObjectIdByImdbId(obj.director);
var movie = new Movie ({
imdbId: obj.id,
title: obj.name,
rank: obj.rank,
rating: obj.rating,
year: obj.year,
director: directorObjId
})