我正在尝试为电子商务商店创建产品更新函数,但 Product.findOneAndUpdate() 始终返回 null。
const updateProduct = await Product.findOneAndUpdate({ id }, req.body, {
new: true,
});
这是我的路线:
const express = require('express');
const {
createProduct,
getaProduct,
getAllProducts,
updateProduct,
} = require('../controller/productCtrl');
const router = express.Router();
router.post('/', createProduct);
router.get('/:id', getaProduct);
router.get('/', getAllProducts);
router.put('/:id', updateProduct);
module.exports = router;
这是我的产品型号:
const mongoose = require('mongoose'); // Erase if already required
// Declare the Schema of the Mongo model
var productSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true,
},
slug: {
type: String,
required: true,
unique: true,
lowercase: true,
},
description: {
type: String,
required: true,
unique: true,
},
price: {
type: Number,
required: true,
},
category: {
type: String,
required: true,
},
brand: {
type: String,
required: true,
},
quantity: {
type: Number,
required: true,
},
sold: {
type: Number,
default: 0,
},
images: {
type: Array,
},
color: {
type: String,
required: true,
},
ratings: [
{
star: Number,
postedby: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
},
],
},
{
timestamps: true,
}
);
//Export the model
module.exports = mongoose.model('Product', productSchema);
这是我用于更新产品的产品控制功能。 它返回 null,我不明白为什么。
const Product = require('../models/productModel');
const asyncHandler = require('express-async-handler');
const slugify = require('slugify');
const updateProduct = asyncHandler(async (req, res) => {
const id = req.params;
try {
if (req.body.title) {
req.body.slug = slugify(req.body.title);
}
const updateProduct = await Product.findOneAndUpdate({ id }, req.body, {
new: true,
});
console.log(updateProduct);
res.json(updateProduct);
} catch (err) {
throw new Error(err);
}
});
module.exports = { createProduct, getaProduct, getAllProducts, updateProduct };
最佳答案
findOneAndUpdate 应该像这样使用 _id
const updateProduct = await Product.findOneAndUpdate({_id: new mongoose.Types.ObjectId(id)}, req.body, {
new: true,
});
关于尝试使用 Express 更新电子商务商店中的产品时,Node.js findOneAndUpdate 函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76394729/