mongodb 我无法使用findByIdAndRemove删除项目

sczxawaw  于 2023-04-11  发布在  Go
关注(0)|答案(1)|浏览(195)
const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");

// getting-started.jsconst mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://127.0.0.1:27017/test');

} //------------------------------------------------//const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

//const items = [];const workItems = [];

const itemsSchema = new mongoose.Schema({
  name: String
});

const Item = mongoose.model('items', itemsSchema);

const item1 = new Item({
  name: "WELCOME "
});
const item2 = new Item({
  name: "hit this to add "
});
const item3 = new Item({
  name: "hit "
});

const defaultItems = [item1, item2, item3];

async function getItems() {

  const Items = await Item.find({});
  return Items;

}

app.get("/", function(req, res) {

  const day = date.getDate();

  getItems().then(function(FoundItems) {
    if (FoundItems.length === 0) {
      Item.insertMany(defaultItems).then(function() {
        console.log("Added successfully!");
      }).catch(function(err) {
        console.log(err);
      });
      res.redirect("/")
    } else {
      res.render("list", {
        listTitle: day,
        newListItems: FoundItems
      });
    }
  });
});

app.post("/", function(req, res) {
  let itemName = req.body.newItem;

  const item = new Item({
    name: itemName
  });

  item.save();
  res.redirect("/");

});

app.post("/delete", function(req, res) {
  const checkedItemId = req.body.checkbox;
  console.log(checkedItemId);
  Item.findByIdAndRemove(checkedItemId).then(function() {
    console.log("Added successfully!");
  }).catch(function(err) {
    console.log(err);
  });

})

app.get("/work", function(req, res) {
  res.render("list", {
    listTitle: "Work List",
    newListItems: workItems
  });
});

app.get("/about", function(req, res) {
  res.render("about");
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});
j91ykkif

j91ykkif1#

使用findOneAndDelete()函数,它对我有用。

Item.findOneAndDelete({ _id: checkedItemId }).then(function() {
    console.log("Removed successfully!");
  }).catch(function(err) {
    console.log(err);
  });

相关问题