我对“猫鼬”和“MongoDB”这两个领域完全陌生。目前,我正试图从数据库中删除一个元素。
到目前为止,这是我的代码:
我的issueModel:
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 !我使用删除方法的post方法:
// 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 (根据我的req.params.ObjectID正确地存储在console.log中),并删除相应的对象。
但目前,当我有一个表,约3-4个条目,总是第一个被删除。为什么会这样呢?我真的是全新的,真的尝试了很多寻找,但我没有找到任何解决办法,直到现在。任何能帮助我的建议我都很高兴。
我做错什么了?URL中的ID和Object.ID是相同的!为什么第一个对象被删除,而不是第二个或第三个?我现在无望了。
我还读到了今天没有真正使用的remove()选项。但我们在大学被告知现在要使用这种方法。我还尝试了在猫鼬数据库中找到的findOneByID和delete方法。
如果您需要更多的代码,请告诉我!
发布于 2018-10-29 13:34:06
您可以为此使用一种方便的方法:findByIdAndRemove
issueModel.findByIdAndRemove(req.params.ObjectId, function(err) {
if (err) { ... failed }
});这将删除与ID匹配的整个文档,我认为这是您想要的,如果您想要从一个不同查询的文档中删除一个remove属性。
如果您不使用只使用ID的方便方法(其中包含ById ),则必须将ID从字符串转换为ObjectId:
const { ObjectId } = require('mongodb');
issueModel.remove({ id: ObjectId(req.params.ObjectId) }).setOptions({ single: true })https://stackoverflow.com/questions/53046455
复制相似问题