猫鼬findOneAndUpdate不会更新我的数据库

时间:2020-03-30 17:22:06

标签: node.js reactjs mongoose axios

我在开发应用程序时正在自学NodeJS。我用猫鼬和Axios。

在应用程序的一个部分上,我显示合作伙伴,当我单击“更新”时,我将获得一个包含所选合作伙伴信息的表格,以便对其进行更新。

客户端将信息发送到服务器,但是服务器不会更新数据库中的条目。这是我的服务器端

app.post("/api/partner/update", (req, res) => {
const id = req.body.id;
const fullname = req.body.fullname;
const email = req.body.email;
const phones = req.body.phones;
const shops = req.body.shops;
const company = req.body.company;

console.log("The body is ",req.body) //It returns the correct data from the client's side submited data

Partner.findOneAndUpdate(id, mongoose.set('useFindAndModify', false),
 {
    "fullname": fullname,
    "email": email,
    "phones": phones,
    "shops":shops,
    "company": company
  },
  (err, document) => {
    if (err) return err;
    //console.log(document);
    res.send({ document });  

  }
);});

这是我的模特:

 const mongoose = require("mongoose");

const partnerSchema = mongoose.Schema(
  {
    fullname: {
      type: String,
      maxlength: 50,
      required: true
    },
    email: {
      type: String,
      trim: true,
      unique: 1,
      required: true
    },
    phones: {
      type: Array
    },
    company: {
      type: String,
      maxlength: 50,
      required: true
    },
    shops: {
      type: Array,
      default: 0
    },
    is_valid: {
      type: Boolean
    },
    validated_by: {
      type: String
    },

    created_by: {
      type: String,
      maxlength: 50
    },
    updated_by: {
      type: String
    },
    deleted_by: {
      type: String
    },
    deleted_at: {
      type: Date,
      default: null
    }
  },
  {
    timestamps: {
      createdAt: "created_at",
      updatedAt: "updated_at"
    }
  }
);

const Partner = mongoose.model("Partner", partnerSchema)
module.exports ={Partner}

我不明白为什么它不更新数据库中的字段

2 个答案:

答案 0 :(得分:1)

引用文档https://mongoosejs.com/docs/tutorials/findoneandupdate.html findOneAndUpdate的第一个参数应该是过滤器对象,而不是直接的id。

所以请尝试Partner.findOneAndUpdate({'_id': id},....

答案 1 :(得分:1)

这是根据文档的findOneAndUpdate的语法:

var query = { name: 'borne' };
Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)

将数据库查询更改为此:

let query = {_id: id };
let dataToUpdate= {
    "fullname": fullname,
    "email": email,
    "phones": phones,
    "shops":shops,
    "company": company
  }
let options = {useFindAndModify: false}  // useFindAndModify set to false at query level
// options = {useFindAndModify: false,new:true} if you want updated docs in return


 Partner.findOneAndUpdate(query,dataToUpdate,options,(err, document) => {
        if (err) return err;
        //console.log(document);
        res.send({ document });  

      }
    )

要在猫鼬级别使用选项启用或禁用弃用警告

mongoose.set('useFindAndModify', false)

在此处了解详情:

Deprecation Warnings

findOneAndReplace

您还可以使用findByIdAndUpdate方法:

Model.findByIdAndUpdate(id, update, options, callback)

您可以启用Promise,使代码更具可读性和可测试性: https://mongoosejs.com/docs/promises.html