Reputation: 79
I am trying to update my mongodb Data with findOneAndUpdate()
. Its not returning any error. Error is null
. But its not also updating any data. In the console I am getting this message:
Mongoose: datas._findAndModify({ _id: undefined }, [], { '$set': { note: undefined, date: undefined, title: undefined }
My Schema:
var mongoose = require("mongoose")
var Schema = mongoose.Schema
var note = new Schema({
title:String,
date:String,
note:String
})
const Data = mongoose.model("Data", note)
module.exports = Data
Server.js:
const express = require('express')
const mongoose = require('mongoose')
var app = express()
var Data = require('./notesSchema')
mongoose.connect('mongoDB://localhost/newDB',{
})
mongoose.connection.once("open", () => {
console.log("connected to DB!")
}).on("error", (error)=>{
console.log("failed to connect" + error)
})
app.get("/hi", (req,res)=>{
res.send("Hello World.")
})
// Create a NOTE
app.post("/create", (req, res)=> {
var note = new Data({
note: req.get("note"),
titile: req.get("title"),
date: req.get("date"),
})
note.save().then(() => {
if(note.isNew == false){
console.log("Saved data!")
res.json({response: "ok"});
}else{
console.log("Failed to save data")
}
})
})
// http://192.168.0.102:8081/create
var server = app.listen(8081, "192.168.0.102", ()=>{
console.log("server is running")
})
mongoose.set('debug', true)
// update a Note
app.post("/update", (req,res)=>{
Data.findOneAndUpdate({
_id: req.get("id")
}, {
title: req.get("title"),
date: req.get("date"),
note: req.get("note"),
},{new: true},(err)=>{
console.log("failed to update " + err)
})
res.send("Updated")
})
// fetch all Notes
app.get("/fetch", (req,res)=>{
Data.find({}).then((DBitems) => {
res.send(DBitems)
})
})
// Delete a Note
app.post("/delete", (req,res) =>{
Data.findOneAndRemove({
_id : req.get("id")
},(err) => {
console.log(err)
})
})
What is wrong here?
Upvotes: 0
Views: 246
Reputation: 41
Your id may be null. Request have params as @AdhamLucasdaSilvaOliveira says.
app.post('/update:id', (req, res) => {
Data.findOneAndUpdate({'_id': req.params.id, {dataset} })
})
if req.get('title') is null try to use req.body.title
Upvotes: 2
Reputation: 662
It depends on where you are passing your parameters.
1) If you pass params in the body with json:
var note = req.body.note;
2) If you pass params with route like /localhost:3000/update/params(id or note)
var note = req.params.note
Upvotes: 1
Reputation: 11
I think that one problem is in the req.get()
because request usually have params and query. So try use req.query.title
if you pass the title like: /example?title=cool
or req.params.title
if you pass the title like: /example/cool
.
Another problem is in:
app.post("/create", (req, res)=> {
var note = new Data({
note: req.get("note"),
->>> titile: req.get("title"),
Because in your Schema,the second field is named title
and not titile
.
Upvotes: 1