【问题标题】:Mongoose / Express findByIdAndUpdate does not workMongoose / Express findByIdAndUpdate 不起作用
【发布时间】:2021-05-26 05:21:47
【问题描述】:

我尝试了 Stackoverflow 和许多其他网站的方法,但无法更改数据库中的数据。我将数据库中产品的 ID 发送到指定的 API。然而,什么都没有回来。数据也不会使用我输入的新 JSON 文件中的数据进行更新。我正在使用 Postman 对其进行测试。

这是我的 server.js 文件中的 API 代码。

app.put("/api/product/update", (req, res) => {
  Product.findByIdAndUpdate(req.params.id, req.body, function (err, doc) {
    res.send(doc);
  });

这是我的模型文件:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = mongoose.Schema({
   
    name: {
        required: true,
        type: String,
        unique: 1,
        //maxlength
    },

    material: {
        type: Array,
        default: []
    },

    price: {
        type: Number,
        required: true,
        maxlength: 255,
    },

    productType: {
        type: Schema.Types.ObjectId,
        ref: 'Prodtype',
        default: "Other",
    },

    inStock: {
        type: Boolean,
        default: true,
    }

},{timestamps:true});

const Product = mongoose.model('Product',productSchema);
module.exports = { Product }

邮递员:PUT localhost:3000/api/product/update?id=6029812bee921b0c7fb65abf

【问题讨论】:

    标签: node.js mongodb express mongoose postman


    【解决方案1】:

    根据您提供的信息,我假设您使用 express 作为您的 nodejs 服务器框架。

    如果您想访问您的请求正文,您需要添加一个body-parser 作为中间件。

    $ npm i body-parser
    
    const bodyParser = require('body-parser')
    
    app.use(bodyParser)
    
    app.put("/api/product/update", (req, res) => {
      Product.findByIdAndUpdate(req.params.id, req.body, function (err, doc) {
        res.send(doc);
      });
    

    此外,我建议您不要将端点上接收到的所有内容直接写入数据库,而是实施某种验证。

    【讨论】:

    • 对不起,我的问题没有解决。我已经在我的项目中使用了 body-parser。无论如何,谢谢。
    【解决方案2】:

    我解决了我的问题。当我如下更改代码时,我使用了 req.query 而不是 req.body。

    app.put("/api/product/update",(req, res) => {
      Product.findByIdAndUpdate(
        { _id: req.query.id },
        { name: req.body.name, price: req.body.price, inStock: req.body.inStock },
        function (err, doc) {
          console.log(doc);
          if (err) {
            console.log(err.message);
          } else {
            res.send(doc);
          }
        }
      );
    });
    

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 2016-12-28
      • 2015-01-22
      • 2023-03-03
      • 2021-10-23
      • 2020-09-25
      • 1970-01-01
      • 2020-08-12
      • 2021-08-26
      相关资源
      最近更新 更多