簡體   English   中英

貓鼬保存多個子文檔

[英]Mongoose save multiple sub-documents

我有一個龐大的收藏集(百萬),叫做User。

User {
   userid: ObjectId,
   person: {ref: 'person', type: ObjectId},
   details: {ref: 'details', type: ObjectId},
   address: {ref: 'address', type: ObjectId},
   other: {ref: 'other', type: ObjectId}
}

它引用了其他集合(人,詳細信息,地址,其他)。

現在,我有了一個用於創建新用戶的API,因此我發送了一個User對象,其中包含所有需要的數據:

user = {
    person: {...},
    details: {...},
    address: {...},
    other: {...}
}

我不想在收藏中重復,所以現在我在做:

let options = {upsert: true, new: true};
let person = await Person.findOneAndUpdate({ personId: user.person.id }, user.person, options);
let details = await Details.findOneAndUpdate({ detailsId: user.details.id }, user.details, options);
let address = await Address.findOneAndUpdate({ addressId: user.address.id }, user.address, options);
let other = await Other.findOneAndUpdate({ otherId: user.other.id }, user.other, options);

然后我設置ID:

user.person = person._id;
user.details = details._id;
user.address = address._id;
user.other = other._id;

然后我保存用戶:

User.findByIdAndUpdate(user._id, user, options)

似乎要進行很多操作,並且由於用戶很大,而且我擁有數百萬個數據,因此,保存1個用戶大約需要1秒,這非常慢。

我怎樣才能更有效地做到這一點?

您通過findOneAndUpdate等待findOneAndUpdate,您應該全部啟動並等待Promise.All:

const allPromise = Array(4);
const options = {upsert: true, new: true};
allPromise[0] = Person.findOneAndUpdate({ personId: user.person.id }, user.person, options);
allPromise[1] = Details.findOneAndUpdate({ detailsId: user.details.id }, user.details, options);
allPromise[2] = Address.findOneAndUpdate({ addressId: user.address.id }, user.address, options);
allPromise[3] = Other.findOneAndUpdate({ otherId: user.other.id }, user.other, options);
const [person,details,address,other] = await Promise.all(allPromise);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM