猫鼬保存多个子文档

时间:2018-12-05 11:09:19

标签: node.js mongodb mongoose

我有一个庞大的收藏集(百万),称为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秒,这很慢。

我如何才能更有效地做到这一点?

1 个答案:

答案 0 :(得分: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);