Node.js findOneAndUpdate函数在尝试使用Express更新电子商务商店中的产品时返回null

dffbzjpn  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(418)

我尝试为电子商务商店创建产品更新函数,但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 };
e5nqia27

e5nqia271#

findOneAndUpdate应该像这样使用_id

const updateProduct = await Product.findOneAndUpdate({_id:  new mongoose.Types.ObjectId(id)}, req.body, {
            new: true,
        });

相关问题