我有兩個端點:一個洗掉產品檔案,一個檢索檔案。
在我通過 Id 洗掉檔案后,GET api 呼叫已經將檔案回傳給我,即使它被洗掉并且它不存在于 MongoDb 上。
DELETE 呼叫回傳的回應 { deletedCount: 1 }
這里獲取產品的代碼:
exports.getSingleProduct = (req, res, next) => {
let id = req.params.id;
Products.findById(id).populate({ path: 'internalColor' }).then(result => {
if(result && result.visible == true) {
res.status(200).json(result)
} else {
res.status(404).json({
message: 'product_not_found',
id: id
})
}
}).catch(err => {
res.status(404).json({
message: 'error_operation: ' err,
id: id
})
});
}
這里洗掉產品的代碼:
exports.deleteDefinallySingleProduct = (req, res, next) => {
let id = req.params.id;
console.log(id)
Products.deleteOne({ id: id }).then(result => {
if(result) {
res.status(200).json({
message: 'deleted_product'
});
}
}).catch(err => {
res.status(404).json({
message: 'error_operation: ' err
})
})
}
產品型號
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const options = {
timestamps: true
}
const productSchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
externalUrl: {
type: String,
required: true
},
imgUrl: {
type: String,
required: true
},
brand: {
type: String,
required: true
},
visible: {
type: Boolean,
required: true
}
}, options);
const Product = mongoose.model('Products', productSchema);
module.exports = Product;
uj5u.com熱心網友回復:
我認為您面臨的錯誤是由代碼中的錯字引起的。
exports.deleteDefinallySingleProduct = (req, res, next) => {
...
Products.deleteOne({ id: id }).then(result => {
if(result) {
// this code will run always
console.log(result) // will show { n: 0, ok: 1, deletedCount: 0 },
// That is, this section of code will run always despite of delete count being 0 or more due to the request to be excecuted successfully.
...
}
正確的實作在這里:
exports.deleteDefinallySingleProduct = (req, res, next) => {
...
Products.deleteOne({ _id: id }).then(result => {
...
}
這是因為默認情況下,mongooose 使用 _id 表示檔案 ID,除非在您沒有執行的架構中創建自定義 ID。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360068.html
標籤:javascript 节点.js 猫鼬
上一篇:錯誤:集合方法聚合是同步的
