我想附加的router.put,这将更新布尔值(IsOn)在切换按钮,但首先我想尝试它是如何工作的,现在我面临的问题。
const express = require("express");
const router = express.Router();
const Buttons = require('../../models/Buttons');
// GET buttons
// This request works perfect
router.get('/', (req,res) => {
Buttons.find()
.sort({name: 1})
.then(buttons => res.json(buttons))
});
// PUT buttons
// This one doesnt work at all
router.put('/:name', function(req,res,next) {
Buttons.findByIdAndUpdate({name: req.params.name},
req.body).then(function(){
Buttons.findOne({name: req.params.name}).then(function(buttons){
res.send(buttons);
});
});
});
module.exports = router;按钮的型号只有name: String,required: true和isOn: Boolean,required: true,db中的数据如下所示:

你能告诉我我做错了什么吗?
按钮模式代码:
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const buttonSchema = new Schema ({
name: {
type: String,
required: true
},
isOn: {
type: Boolean,
required: true
}
});
module.exports = Buttons = mongoose.model("buttons", buttonSchema);发布于 2020-01-17 18:38:31
只有当您希望通过匹配文档的_id来更新文档时,才能使用findByIdAndUpdate
如果希望通过任何其他属性(如本例中的name )匹配文档,则可以使用findOneAndUpdate
像这样编写您的查询
router.put('/:name', function(req,res,next) {
Buttons.findOneAndUpdate({name: req.params.name},
req.body).then(function(){
Buttons.findOne({name: req.params.name}).then(function(buttons){
res.send(buttons);
});
});
});希望这能有所帮助
发布于 2020-01-17 17:50:42
请同时添加您的id,以便在数据库中进行更新
Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...出现这个错误是因为findByIdAndUpdate需要一个我们想要更新的对象的id,所以它显示了ObjectId错误。因此,从前端传递您的id并在后端使用它来更新颗粒数据。
第1步:您可以为update-name创建新端点
router.put('/update-name', function(req,res,next) {
//here you can access req.body data comes from front-end
// id = req.body.id and name = req.body.name then use it in your
Buttons.findByIdAndUpdate(id, { name : name }, {new: true}, function(err, model) {...
}第2步:尝试这个端点/update-name,并在Body中从postman传递数据
https://stackoverflow.com/questions/59784576
复制相似问题