猫鼬:删除项目-第一个总是被删除

时间:2018-10-29 13:24:13

标签: mongodb mongoose

我对Mongoose和MongoDB领域完全陌生。 我目前正在尝试从数据库中删除一个元素。

到目前为止,这是我的代码:

我的问题模型:

var mongoose = require('mongoose');  // loading module for mongoose
var db = mongoose.connect('mongodb://localhost/issuedb');

var issueSchema = new mongoose.Schema({
    title: String,
    description: String,
    priority: String,
    status: String
});

// Constructor Function:
var issueModel = mongoose.model('issues', issueSchema); // have to give the 
name of the collection where the element should be stored + Schema

// Export this Construction Function for this Module:
module.exports = issueModel;  // careful: module != model !

我使用删除方法的发布方法:

// creating the router for deleting one item:

router.post('/delete/:id', (req, res) => {

console.log(req.params.id);
issueModel.remove({id: req.params.ObjectId})
.setOptions({ single: true }).exec(function (err, deleted) {})
.then(issues => res.render('issue', {issues: issues}));

我想在这里使用对象ID-根据我的console.log将其正确存储在req.params.ObjectID中,然后删除相应的对象。

但是目前,当我有一张约有3-4个条目的表时,总是第一个被删除。这是为什么?我真的是完全新手,确实尝试了很多搜索,但是直到现在我都找不到任何解决方案。对于可以帮助我的任何提示,我都很高兴。

我在做什么错? URL中的ID和Object.ID相同!为什么要删除第一个对象,而不删除第二个或第三个对象? 我现在绝望了。

我还读到了remove()选项在当今时代并未真正使用。但是我们被告知大学现在要使用这种方法。 我还尝试了findOneByID并删除了在猫鼬数据库中找到的方法。

如果您需要更多代码,请告诉我!

1 个答案:

答案 0 :(得分:1)

您可以使用以下一种便捷方法:findByIdAndRemove

issueModel.findByIdAndRemove(req.params.ObjectId, function(err) {
  if (err) { ... failed }
});

如果要从另一个查询的文档中删除属性,这将删除与我认为所需的ID相匹配的整个文档。

如果您不使用仅使用ID的便捷方法之一(其中包含ById),则必须将ID从字符串转换为ObjectId:

const { ObjectId } = require('mongodb');

issueModel.remove({ id: ObjectId(req.params.ObjectId) }).setOptions({ single: true })