我正在使用猫鼬,我想搜索多个集合并使用_id属性删除。
我正在从用户那里收到一个_id数组,并且我正在尝试遍历每个元素。
var express = require("express");
const mongoose = require("mongoose");
const router = express.Router();
router.delete("/", async (req, res) => {
let data = req.body; // this is an array of _id from the user
data.forEach((element) => {
let models = [];
models.push(mongoose.models.Furniture);
models.push(mongoose.models.Clothing);
models.map((model) => model.findByIdAndRemove(element));
});
});
module.exports = router;
运行此程序时,我没有收到任何错误。
答案 0 :(得分:1)
MongoDB操作是异步操作。因此,要获取错误或结果,您需要等待数据库返回响应。
var express = require("express");
const mongoose = require("mongoose");
const router = express.Router();
router.delete("/", async (req, res) => {
let data = req.body; // this is an array of _id from the user
data.forEach((element) => {
let models = [];
models.push(mongoose.models.Furniture);
models.push(mongoose.models.Clothing);
try {
models.map(async (model) => { await model.findByIdAndRemove(element)});
} catch (error) { console.log(error) }
});
});
module.exports = router;
Note: this code is not tested locally but the problem I have solved here