简体   繁体   中英

.save is not a function, and .findOneAndUpdate() doesn't update my db

I'm setting up a backend server, and i want to do a put method in router. I'm using mongoose express in backend.

When i'm trying update some data in my db with .save() , i get error:

events.js:174 throw er; // Unhandled 'error' event ^

TypeError: PC.save is not a function

I'm trying another soulution with .findOneAndUpdate(), it is success but it doesn't update my database.

const express = require('express')
const routes = express()

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp',  { useNewUrlParser: true });
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error"));
db.once("open", function(callback){
  console.log("Connection Succeeded");
});

var PC = require("../models/PC");

//...here is my get delete etc..

This is my first solution with findOneAndUpdate

routes.put('/:id', (req, res) => {
 mongoose.set('useFindAndModify', false);
  PC.findOneAndUpdate(
    { 'title': req.body.title }, 
    { '$set': {'description': req.body.description} },
    {'new': true },
    function(err, PC) {
        if (err) {
          console.log('ERROR WHILE PUT PC');
            throw (err);
        } else {
            console.log('Succes set');
            res.status(200).send(PC)
        }
    }
  );
})

And this is my second solution

routes.put('/:id', (req, res) => {
  PC.findById(req.params.id, 'title description', function (error, pc) {
    if (error) { console.error(error); }

    PC.title = req.body.title
    PC.description = req.body.description
    console.log(PC);
    PC.save(function (error) {
      if (error) {
        console.log(error)
      }
      res.send({
        success: true,
        message: 'PC saved successfully!',
        PC: req.body
      })
    })
  })
})

module.exports = routes;

my model:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var PCSchema = new Schema({
  id: Number,
  brand: String,
  cpu: String,
  memory: Number,
  type: String,
  vga: String,
  score: Number,
  title: String,
  description: String
});

var PC = mongoose.model("PC", PCSchema);
module.exports = PC;

In your first example it looks like you are finding with the wrong param, and you should be using id .

Try using findByIdAndUpdate instead:

routes.put('/:id', (req, res) => {
 mongoose.set('useFindAndModify', false);
  PC.findByIdAndUpdate( 
    req.params.id,
    { '$set': {'description': req.body.description, 'title': req.body.title} },
    {'new': true },
    function(err, pc) {
        if (err) {
          console.log('ERROR WHILE PUT PC');
            throw (err);
        } else {
            console.log('Succes set');
            res.status(200).send(pc)
        }
    }
  );
})

In you second example, you should be calling .save on the result, not the original PC Model . You could change that to:

routes.put('/:id', (req, res) => {
  PC.findById(req.params.id, 'title description', function (error, pc) {
    if (error) { console.error(error); }

    // Use lowercase `pc` on all these lines
    pc.title = req.body.title
    pc.description = req.body.description
    console.log(pc);
    pc.save(function (error) {
      if (error) {
        console.log(error)
      }
      res.send({
        success: true,
        message: 'PC saved successfully!',
        PC: req.body
      })
    })
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM