我正在使用ExpressJS + MongoDB + TypeScript。以下是我的模型
export class Author {
name: string;
dob: Date;
}
export class Publisher {
name: string;
address: string;
}
import {Author} from './Author';
import {Publisher} from './Publisher';
export class Book {
name: string;
price: number;
author: Author;
publisher: Publisher;
}
我已按以下方式插入数据
let publisher1: Publisher = new Publisher();
publisher1.name = "Publisher 1";
publisher1.address = "Amritsar";
let publisher2: Publisher = new Publisher();
publisher2.name = "Publisher 2";
publisher2.address = "Bangalore";
let author1: Author = new Author();
author1.name = "Author 1";
author1.dob = new Date();
let author2: Author = new Author();
author2.name = "Author 2";
author2.dob = new Date();
let book1: Book = new Book();
book1.name = "Book 1";
book1.price = 50;
book1.author = author1;
book1.publisher = publisher1;
let book2: Book = new Book();
book2.name = "Book 2";
book2.price = 100;
book2.author = author2;
book2.publisher = publisher2;
let book3: Book = new Book();
book3.name = "Book 3";
book3.price = 150;
book3.author = author1;
book3.publisher = publisher2;
创建了3个集合,即发布者(2个文档),作者(2个文档)和书籍(3个文档)。
现在,当我使用以下代码将作者1 的名称更新为作者5 时,它会在作者集合中更改。
this.db.collection('Author').findOneAndUpdate({
name: "Author 1"
}, {
$set: {
name: "Author 5"
}
})
但是当我查询名为第1册或第3册的书籍时,它仍然引用名称作者1 而不是作者5
在参考图书集中的文件时是否有问题?
答案 0 :(得分:1)
您指定Book架构中的author
字段具有与Author架构相同的架构。当您创建一本书并将作者记录作为字段author
的值传递给它时,您将直接在Book记录中设置值。它没有将两个记录链接在一起。要更新两个记录中的名称,您必须更新作者集合中的名称以及Book集合中每个相应记录的名称。