Node.js Mongoose保存多个子文档

Node.js Mongoose保存多个子文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个巨大的集合(百万),叫做用户 User { userid: ObjectId, person: {ref: 'person', type: ObjectId}, details: {ref: 'details', type: ObjectId}, address: {ref: 'address', type: ObjectId}, other: {ref: 'other', type: ObjectId} } 它引用了其他集合(人员、详细信息、地址、其他)

我有一个巨大的集合(百万),叫做用户

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 = {
    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秒,这相当慢


我怎样才能更有效地完成这项工作?

如果你一个接一个地等待findOneAndUpdate,你应该开始所有的工作,并承诺等待。所有:

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);

我有其他地方可以这样做,我得到了显着的速度提高,我把这作为一个答案!谢谢你提醒我承诺