简体   繁体   中英

how to use of objectId in nodejs

I write 2 models in mongoose. first for Users another for Movies. I wrote this models below. first I save my all user in users collection. after that I want to save my movies to movies collection. but when I want to define my director field I get an error that "ReferenceError: director is not defined"

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}

and this is my function:

 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)

Move the await findObjectIdByImdbId(obj.director) out of Movie initialization

Eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM