未更新MongoDB引用的值
我正在使用ExpressJS+MongoDB+TypeScript。下面是我的模型未更新MongoDB引用的值,mongodb,express,Mongodb,Express,我正在使用ExpressJS+MongoDB+TypeScript。下面是我的模型 我已经插入了如下数据 let publisher1: Publisher = new Publisher(); publisher1.name = "Publisher 1"; publisher1.address = "Amritsar"; let publisher2: Publisher = new Publisher(); publisher2.name = "Publisher 2"; pub
我已经插入了如下数据
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"
}
})
但是当我查询名为Book1或Book3的图书时,它仍然引用名为作者1,而不是作者5
引用图书集合中的文档时是否有问题?您正在指定图书架构中的
author
字段具有与author架构相同的架构。当您创建一本书并将作者记录作为字段author
的值传递给它时,您可以直接在书记录中设置这些值。它不是将这两个记录链接在一起。为了更新两个记录中的名称,您必须更新作者集合中的名称以及图书集合中每个相应记录的名称。我阅读了有关此问题的更多信息,发现有不同的方法来处理此问题。我试的那个是不正确的。谢谢你的帮助。
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;
this.db.collection('Author').findOneAndUpdate({
name: "Author 1"
}, {
$set: {
name: "Author 5"
}
})