節點表明我這個錯誤,當我做一個PUT請求:的NodeJS - 快 - 貓鼬:PUT請求問題,保存方法
TypeError: product.save is not a function
(指save
功能控制器/ product.js)
我覺得這是更新文檔的正確形式,但是我有這個問題。代碼
我分享部分:
app.js
var api = express.Router();
api.route('/products')
.get(ProductCtrl.findAll)
.post(ProductCtrl.add);
api.route('/products/:isbn')
.get(ProductCtrl.findByISBN)
.delete(ProductCtrl.delete)
.put(ProductCtrl.update);
app.use('/api', api);
型號/ product.js
var mongoose = require('mongoose');
var Schema = mongoose.schema;
var productSchema = mongoose.Schema({
isbn: {type: String},
title: {type: String},
author: {type: String},
template: {type: String},
active: {type: Number} //1 - Active, 0 - Inactive
});
module.exports = mongoose.model('Product', productSchema);
控制器/ product.js
//PUT - Update the product by ISBN
exports.update = function(req, res){
Product.find(req.params.isbn, function(err, product){
if(!product) res.status(404).send({message: 'Product not exits'});
console.log("PUT - /products/" + req.params.isbn);
product.isbn = req.body.isbn;
product.title = req.body.title;
product.author = req.body.author;
product.active = req.body.active;
product.template = req.body.template;
product.save(function(err){
if(err) return res.send(500,err.message);
console.log("Successfully updated: " + req.body.isbn);
res.status(200).json(product);
});
});
};
謝謝Rajesh Dan,我使用了Model.findOneAndUpdate(),並且按預期工作! –
當然,很高興幫助。 @AlfonsoSánchez! :) –