node项目连接mongodb删除多条数据
删除前
删除后
index.js
const {
server
} = require('./server/index')
const {
connectDB
} = require("./db/index.js")
const Model = require("./model/user")
// 连接mongodb数据库
connectDB().then(res => {
})
// 监听请求
server.on('request', async function (req, res) {
const {
method,
url,
} = req
if (method === 'GET') {
if (url === '/user') {
// 查找集合中的数据(user)
const data = await Model.find();
res.end(JSON.stringify({
code: 0,
data: {
list: data || []
}
}))
}
} else if (method === 'DELETE') {
if (url === '/user') {
// 查找集合中的数据(user)
const data = await Model.find({
name: '木子'
});
const idList = data.map(v => v._id)
const list = await Model.deleteMany({
_id: {
$in: idList || []
}
});
res.end(JSON.stringify({
code: 0,
data: {
list: data || [],
lo: list
}
}))
}
}
})
server.listen(3000, "localhost", () => {
// console.log('listen');
})
model\user.js
const mongodb = require('mongoose')
const Schema = mongodb.Schema;
const UserModel = new Schema({
name: String,
id: String,
tel: String,
hobby: String,
updateDate: String,
})
const Model = mongodb.model('UserModal', UserModel, 'user');
module.exports = Model
server\index.js
const http = require('http')
const server = http.createServer(function (req, res) {})
module.exports = {
server
}
删除数据处理,与上文无关
删除数据
const del = async (params) => {
// 找到需要删除的数据_id
let idList = [];
// 查找集合中的数据(user)
const data = await Model.find(params);
let res = {
code: 0
}
console.log('data', data);
if (data.length) {
idList = data.map(v => v._id)
const result = await Model.deleteMany({
_id: {
$in: idList || []
}
});
if (result.deletedCount) {
res = {
code: 0,
data: null,
msg: errorMsg['1']
}
}else{
res = {
code: 10001,
data: null,
msg: errorMsg['900010']
}
}
} else {
res = {
code: 10001,
data: null,
msg: errorMsg['10001']
}
}
return res
}