无法保存多对多关系模型(猫鼬)的属性

时间:2020-11-03 22:28:10

标签: javascript node.js async-await many-to-many mongoose-schema

我正在创建一家书店,我有3种模型:书本,作者和类型。 书籍存储着一个作者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)UnhandledPromiseRejectionWarning:VersionError:未找到ID为“ 5fa1dbbb969d727164f1f59e”版本0的匹配文档,修改了路径“类型” 在generateVersionError(C:\ Users \ sasha \ Desktop \ Bookstore \ node_modules \ mongoose \ lib \ model.js:421:10) 在model.Model.save(C:\ Users \ sasha \ Desktop \ Bookstore \ node_modules \ mongoose \ lib \ model.js:478:28) 在C:\ Users \ sasha \ Desktop \ Bookstore \ seed.js:234:34 在C:\ Users \ sasha \ Desktop \ Bookstore \ node_modules \ mongoose \ lib \ model.js:4844:16 在C:\ Users \ sasha \ Desktop \ Bookstore \ node_modules \ mongoose \ lib \ model.js:4844:16 在C:\ Users \ sasha \ Desktop \ Bookstore \ node_modules \ mongoose \ lib \ helpers \ promiseOrCallback.js:24:16 在C:\ Users \ sasha \ Desktop \ Bookstore \ node_modules \ mongoose \ lib \ model.js:4867:21 在C:\ Users \ sasha \ Desktop \ Bookstore \ node_modules \ mongoose \ lib \ query.js:4420:11 在C:\ Users \ sasha \ Desktop \ Bookstore \ node_modules \ kareem \ index.js:135:16 在processTicksAndRejections(内部/进程/task_queues.js:79:11) 在runNextTicks(内部/进程/task_queues.js:66:3) 在processImmediate(internal / timers.js:434:9)

在数据库书籍中 arrays with authors are filed. Ganres arrays are not The problem might be in book.save() calls from connectBooksToAuthors and connectBooksToGenres but I don真的不知道如何解决

0 个答案:

没有答案