简体   繁体   English

Mongoose 创建操作在删除操作后无法立即运行

[英]Mongoose Create operation(s) not working immediately after Delete operation(s)

I am trying to repopulate my collection on an API call using the data I receive.我正在尝试使用收到的数据在 API 呼叫中重新填充我的收藏。 I basically want to wipe of the entire collection(s) and repopulate them with the new data I have received in my API call.我基本上想擦除整个集合并用我在 API 电话中收到的新数据重新填充它们。

The creation operations work fine if I don't run the delete operations.如果我不运行删除操作,创建操作就可以正常工作。 However if I try running the delete operations first, no new documents are created.但是,如果我先尝试运行删除操作,则不会创建任何新文档。

Here is a stripped down version of my controller function:这是我的 controller function 的精简版:

let { data } = req.body
try {
    let result = await Record.deleteMany({});
} catch (err) {
    res.status(400).json('Unable to clean database');
}
for (let i in data) {
    await Record.create(data[i]);
}
return res.status(200).json('Successfully Processed CSV')

How do I go about resolving this?我怎么go解决这个问题? Basically all I want is to delete all documents within the collection and add the new documents immediately after.基本上我想要的只是删除集合中的所有文档并在之后立即添加新文档。

use for of if data is an array of objects you can do like this:使用for of if data 是一个对象数组,你可以这样做:

let { data } = req.body
for (let newRecord of data) {
    await Record.create(newRecord );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM