Javascript 无法将may的属性保存到多个关系模型(mongoose)

Javascript 无法将may的属性保存到多个关系模型(mongoose),javascript,node.js,async-await,many-to-many,mongoose-schema,Javascript,Node.js,Async Await,Many To Many,Mongoose Schema,我正在创建一家书店,我有三种模式:书籍、作者和流派。 Books存储作者ID数组和流派ID数组。作者存储图书ID数组。流派也有书籍ID数组 BookSchema = new mongoose.Schema({ title: String, authors: [ { type: mongoose.Schema.Types.ObjectId, ref: "Author" }

我正在创建一家书店,我有三种模式:书籍、作者和流派。 Books存储作者ID数组和流派ID数组。作者存储图书ID数组。流派也有书籍ID数组

    BookSchema = new mongoose.Schema({
    title: String,
    authors: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Author"
        }
    ],
    image: String,
    description: String,
    price: Number,
    genres: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Genre"
        }
    ],
});


AuthorSchema = new mongoose.Schema({
    name: String,
    books: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Book"
        }
    ],
});

GenreSchema = new mongoose.Schema({
    name: String,
    books: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Book"
        }
    ],
});
然后我有一个数据数组,它存储关于我们需要创建的书的信息

{
        title: "The Monster at the End of This Book",
        authors: ["Jon Stone"],
        img: "https://images-na.jpg",
        price: "0.35",
        description: "Carve out family time for ...",
        genres: ["Children's Humour (Books)"]
    },
我正在尝试添加作者、流派和书籍。之后,我想把作者和书联系起来

Book.deleteMany({}, () => {
    insertBooks().then(insertGenres).then(insertAuthors).then(connectBooksToAuthors);
}).then(function () {
    connectBooksToGenres();
})

async function insertAuthors() {
    let authorsArr = [];
    data.forEach(dataPiece => {
        dataPiece.authors.forEach(author => {
            if (authorsArr.indexOf(author) === -1) {
                authorsArr.push(author)
            }
        })
    })
    authorsArr.forEach(author => {
        Author.findOne({name: author}, (err, a) => {
            if (!a) {
                Author.create({name: author});
            }
        })
    })
}

async function insertGenres() {
    let genresArr = [];
    data.forEach(dataPiece => {
        dataPiece.genres.forEach(genre => {
            if (genresArr.indexOf(genre) === -1) {
                genresArr.push(genre);
            }
        })
    })
    genresArr.forEach(genre => {
        Genre.findOne({name: genre}, (err, g) => {
            if (!g) {
                Genre.create({name: genre});
            }
        })
    })
}

async function insertBooks() {
    data.forEach((dataPiece) => {
        let obj = {
            "title": `${dataPiece.title}`,
            'description': `${dataPiece.description}`,
            "price": `${dataPiece.price}`,
        };
        Book.create(obj);
    })
}

async function connectBooksToAuthors() {
    data.forEach(dataPiece => {
        Book.findOne({"title": `${dataPiece.title}`}, (err, book) => {
            let authorsArr = [];
            dataPiece.authors.forEach(authorsName => {
                Author.findOne({name: authorsName}, (err, author) => {
                    author.books.push(book);
                    author.save();
                    authorsArr.push(author);
                     if (authorsArr.length === dataPiece.authors.length) {
                         book.authors = [...authorsArr];
                         book.save();
                     }
                });

            });
        })
    })
}

async function connectBooksToGenres() {
    data.forEach(dataPiece => {
        Book.findOne({"title": `${dataPiece.title}`}, (err, book) => {
            let genresArr = [];
            dataPiece.genres.forEach(genreName => {
                Genre.findOne({name: genreName}, (err, genre) => {
                    genre.books.push(book);
                    genre.save();
                    genresArr.push(genre);
                    if (genresArr.length === dataPiece.genres.length) {
                        book.genres = [...genresArr];
                        book.save();
                    }
                });

            });
        })
    })
}
当我运行代码时,会出现以下异常: (节点:29028)未经处理的PromisejectionWarning:VersionError:找不到id为“5FA1DBB969D727164F1F59E”版本0 ModifiedPath“流派”的匹配文档 生成时出错(C:\Users\sasha\Desktop\Bookstore\node\u modules\mongoose\lib\model.js:421:10) 在model.model.save(C:\Users\sasha\Desktop\Bookstore\node\u modules\mongoose\lib\model.js:478:28) 在C:\Users\sasha\Desktop\Bookstore\seed.js:234:34 在C:\Users\sasha\Desktop\Bookstore\node\u modules\mongoose\lib\model.js:4844:16 在C:\Users\sasha\Desktop\Bookstore\node\u modules\mongoose\lib\model.js:4844:16 在C:\Users\sasha\Desktop\Bookstore\node\u modules\mongoose\lib\helpers\promiseOrCallback.js:24:16 在C:\Users\sasha\Desktop\Bookstore\node\u modules\mongoose\lib\model.js:4867:21 在C:\Users\sasha\Desktop\Bookstore\node\u modules\mongoose\lib\query.js:4420:11 在C:\Users\sasha\Desktop\Bookstore\node\u modules\kareem\index.js:135:16 在处理和拒绝时(内部/process/task_queues.js:79:11) 在runNextTicks(internal/process/task_queues.js:66:3) 在processImmediate(internal/timers.js:434:9)


在数据库中,作者的数组被归档。Ganres数组不是问题可能在book.save()中,从ConnectBooks到Authors和connectBooksToGenres的调用,但我不知道如何修复它?您还没有真正告诉我们您的具体问题是什么。抱歉,在问题的末尾添加了您的代码使用
。然后()
回调,但乍一看,您的函数没有在任何地方使用
wait
。这可能意味着您的函数依赖于尚未创建的对象。