I am having trouble with a simple query on my database. Following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 when Model.find() is called, he receives a JSON object back with the name field (the only custom field) and the _id and __v. When I do the same, all I receive back is the _id and __v field. I do get a successful response back saying the post was created, but it doesn't include the title or content fields. Yet a query shows that the data was never saved.
Routing and query:
var express = require("express");
var router = express.Router();
var Post = require("../app/models/post.js");
/* Drop Post collection
Post.remove({}, function(err, num_docs) {
if (err) {
res.send(err);
} else {
console.log("Collection dropped, documents deleted: " + num_docs);
}
});
*/
// Middleware for all routes.
router.use(function(req, res, next) {
console.log("API request made.");
next(); // Go to next routes, don't stop here
});
// Test route to ensure routing is working
router.get("/", function(req, res) {
res.json({
message: "Hooray! Welcome to the API!"
});
});
// On routes that end in /posts
router.route("/posts")
// Create post. (Accessed at POST http://localhost/api/posts)
.post(function(req, res) {
var post = new Post(); // Create new instance of post model
post.title = req.body.title; // Set title (from request)
post.content = req.body.content; // Set content (from request)
// Save the post, and check for errors.
post.save(function(err) {
if (err) {
res.send(err);
} else {
res.json({
message: "Post created!",
title: post.title,
content: post.content
});
}
});
})
.get(function(req, res) {
Post.find({}).exec(function(err, posts) {
if(err) {
res.send(err);
} else {
res.json(posts);
}
});
});
module.exports = router;
Response:
[
{
"_id": "56a6adc31f06c4dc1cf82888",
"__v": 0
},
{
"_id": "56a9768888f806dc1fe45415",
"__v": 0
},
{
"_id": "56a97f3f4e269b7c21311df8",
"__v": 0
}
]
A db query in the shell returns the same information, just an _id and __v field.
I am beyond confused right now. It suddenly works, the code is the exact same as above. I am going to leave this open in case someone stumbles across it one day and can solve this mystery.
The problem is that you need to set the content-type while sending the post request as application/json otherwise the fields are not recognized.
I experienced an error like this.
The problem was that I was loading the wrong mongoose Schema.
The result is that the only fields that are saved are those that are present in both schemas, i.e. _id and __v.
For this code
post.title = req.body.title; // Set title (from request)
post.content = req.body.content; // Set content (from request)
could you check
req.body.title and req.body.content are not undefined?
do you set the field in your Post schema as
var PostSchema = new Schema({
title: String,
content: String
});
If you are using a manual tool like Postman to test your app, you must also put quotes around the key names in the body of your request, like {"key": "some string"}.
If you just put {key: "some string"} then the whole key/value pair is ignored when the document is saved to the database.
Exact same thing happened to me...
First two POSTs succeeded but did not post the data I was sending:
var p = new Post();
p.result = 'hello-world';
p.save(function (err) {});
Turned on debug mode: mongoose.set('debug', true); and next POST the field was saved...
Baffling!
Related
The existing code was written as MySQL query and I am now working on converting it to Mongoose query.
I need to get five data sorted by the most recent subscription year from the main page.
The existing code brought this result value into an array. And data was delivered through pug view, and Mongoose seems to bring the result value of Object. In this case, I wonder how to deliver the data through Pug view.
I checked importing data from the terminal to the console.log, but an error called 'Error [ERR_HTTP_HEADERS_SENT]: Cannot set heads after they are sent to the client occurs and no data is passed to the pug. I wonder why this problem occurs.
[MySQL Query]
router.get("/", function (req, res, next) {
// Main page Profile Data Process
db.query(`SELECT * FROM user ORDER BY registerDate DESC LIMIT 5`, function (
error,
data
) {
// Log Error
if (error) {
console.log(error);
}
res.render("main", {
dataarray: data,
_user: req.user,
url: url
});
});
});
[Mongoose Query]
router.get("/", function (req, res, next) {
let dataarray = [];
let userData = db.collection("user").find().limit(5).sort({
"created_at": -1
});
userData.each(function (err, doc) {
if (err) {
console.log(err);
} else {
if (doc != null) {
dataarray.push(doc)
}
}
// console.log(dataarray.login)
console.log(dataarray);
res.render("main", {
dataarray,
_user: req.user
})
});
});
[pug file]
each profile in dataarray
.col-lg-4
img.rounded-circle(src=`${profile.avatar_url}` alt='Generic placeholder image' width='140' height='140')
h2=`${profile.login}`
p=`${profile.bio}`
p
a.btn.btn-secondary(href=`/${profile.login}` role='button') View details ยป
You are sending the request in multiple chunks, node/express uses one request and one response.
Cannot set heads after they are sent to the client
Is the error that happens when the res.render is called the second time. At this point, the one request has already left the node/express process and this is tell you that you're trying to violate the one request/one response paradigm.
This is the part of your code where you can see why this happens.
router.get("/", function (req, res, next) {
let dataarray = [];
let userData = db.collection("user").find().limit(5).sort({
"created_at": -1
});
userData.each(function (err, doc) {
This part of your code will try to send a response for each item in your resultset.
Something like this will work properly (I didn't test it):
router.get("/", function (req, res, next) {
db.collection("user").find().limit(5).sort({ "created_at": -1 }, function(err, userData){
res.render("main", {
dataarray: userData,
_user: req.user
})
});
});
In other words, only one res.render is required and pass the entire result set into that.
I am making an api rest in which I want to make HTTP requests using Postman, specifically I want to perform a search or update a mongodb document, but this must be by an id which is not the doc_id that provides mongo
models Schema
'use strict'
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const infoClientSchema = Schema ({
idusr: String, /*this is require*/
name: String,
phone: Number,
address: String,
riff: String,
state: String,
city: String,
email: {type: String}
})
module.exports = mongoose.model('InfoCli',infoClientSchema)
Controller (This is the get method I know using findById and is working)
'use strict'
const InfoCli = require('../models/infoclient')
function getInfoCli(req, res){
let infocliId = req.params.infocliId
InfoCli.findById(infocliId, (err, infocli) =>{
if (err) return res.status(500).send({message: 'Error making
request: $(err)'})
if (!infocli) return res.status(404).send({message: 'The client does
not exist '})
res.status(200).send({infoclient: infocli})
})
}
Controller (This is the get method which I thought would work using findOne)
function getInfoByUsr(req, res){
let idusr = req.body.idusr
InfoCli.findOne(idusr, (err, infocli) => {
if (err) return res.status(500).send({message: 'Error making
request: $(err)'})
if (!infocli) return res.status(404).send({message: 'The client does
not exist '})
res.status(200).send({infoclient: infocli})
console.log(infocli) /*The console is not showing anything*/
})
}
Controller (This is the put method which I thought would work using findOneAndUpdate)
function updateByUsr(req, res){
let idusr = req.body.idusr
let update = req.body
InfoCli.findOneAndUpdate(idusr, update, (err, infocliUpdate) => {
if (err) return res.status(500).send({message: 'Error making
request: $(err)'})
if (!idusr) return res.status(404).send({message: 'The client does
not exist '})
res.status(200).send({infocliente: infocliUpdate})
})
}
Routes (not 100% sure about this)
const express = require('express')
const InfoCliCtrl = require('../controllers/infoclient')
const api = express.Router()
api.get('/infoclient/:infocliId', InfoCliCtrl.getInfoCli) /*working*/
api.get('/infoclient/:idusr', InfoCliCtrl.getInfoByUsr)
In your app.js/server.js
you should have bodyparser installed
api.get('/infoclient/:infocliId', InfoCliCtrl.getInfoCli)
api.post('/infoclient/:idusr', InfoCliCtrl.updateByUsr)
If you are passing data as URL parameter, like this /infoclient/:infocliId then you can access that using req.params.infocliId
If you are passing using POST body then you can access data using req.body.
In infoClient.js
To fetch user data
exports.getInfoCli = function(req, res, next){
var incomingData = req.params.infocliId;
InfoCli.findOne({idusr: incomingData}, function(err, data){
if(err){
return res.status(500);
} else {
return res.status(200).send({infoclient: data})
}
});
}
Call the above code by
GET - http://localhost:port/infoclient/3874234634 this 3874234634 is your infocliId you need to pass in route
To update user data
exports.updateByUsr = function(req, res, next){
var userId = req.params.idusr;
var updateData = req.body;
InfoCli.findOneAndUpdate({idusr: userId}, updateData, {new: true }, function(err, data){
if(err){
return res.status(500);
} else {
return res.status(200).send(data)
}
});
}
In the update code we have used {new : true} is to return updated document from DB
Call the above code by
POST method - http://localhost:port/infoclient/3874234634 with data in POST body {name: 'pikachu', phone: 12345, ...}
so you read the userid in url parameter using req.params and body data in req.body
I think you simply need to change the line let idusr = req.body.idusr in your getInfoByUsr() function to let idusr = req.params.idusr
http://expressjs.com/en/api.html#req.body
http://expressjs.com/en/api.html#req.params
Also check the syntax of your findOne and findOneAndUpdate query (because idusr is not a Mongo _id but sort of custom String id):
InfoCli.findOne({ idusr: idusr }, (err, infocli) => { ...
InfoCli.findOneAndUpdate({ idusr: idusr }, update, (err, infocliUpdate) => {..
http://mongoosejs.com/docs/api.html#model_Model.findOne
Thank you all, your answers help me to correct many things in the code.
The problem was a horrible mistake in the routes
See how I was using the same path for two requests
api.get('/infoclient/:infocliId', InfoCliCtrl.getInfoCli) /*working*/
api.get('/infoclient/:idusr', InfoCliCtrl.getInfoByUsr)
The problem was that when I used the identifier for idusr it was in conflict with the ObjectId search
Now
api.get('/infoclient/idusr/:idusr', InfoCliCtrl.getInfoByUsr)
I want to retrieve data from the database using the Mongoose Model.find() function, passing along whatever parameters I get from req.body as well as the parameter req.user._id as my query.
So far what I've done is put the req.user._id inside my req.body and then passing them to Post.find() as follows:
getUserPosts: function(req, res) {
req.body.user = "" + req.params.id;
var query = JSON.stringify(req.body);
Post.find(query, function(err, posts) {
if(err) return res.status(500).json({error: unknownError});
else if(posts) return res.status(200).json({posts});
});
}
The problem is; I keep getting data results that do not match the query I am sending. What could I possibly be doing wrong here?
Firstly... remove that JSON.stringify part. The query parameter requires key/value object comprising of field names (key) that should match with values specified. For example var query = { _id: req.body._id }.
Second... What is that req.body.user = req.params.id?
Final code:
getUserPosts: function(req, res) {
var query = { _id: req.params.id };
Post.find(query, function(err, posts) {
if(err) return res.status(500).json({error: unknownError});
else if(posts) return res.status(200).json({posts});
});
}
You defined that req.body.user = "" + req.params.id;
I don't know whether the params.id is the Post.user in the post.
Whatever, your req.body became {user: id}
I suggest you print out the object of req.body and see whether it exists in your Post model in mongodb.
Besides, in mongodb, the generated _id is an ObjectId instead of string. You are supposed to login to mongodb and understand the format of the data.
See the following example in mongo:
> db.Post.find({"_id":"5786d286ed4b71f473efbd99"})
// nothing
> db.Post.find({"_id":ObjectId("5786d286ed4b71f473efbd99")})
{ "_id" : ObjectId("5786d286ed4b71f473efbd99"), "created" : ISODate("2016-07-13T23:45:10.522Z") }
I have a schema problem. I dont get the right schema in my api. here is my api :
var Meetup = require('./models/meetup');
module.exports.create = function (req, res) {
var meetup = new Meetup(req.body);
meetup.save(function (err, result) {
console.log(result);
res.json(result);
});
}
module.exports.list = function (req, res) {
Meetup.find({}, function (err, results) {
res.json(results);
});
}
The console.log displays { __v: 0, _id: 58343483ff23ad0c40895a00 } while it should display { __v: 0, name: 'Text input', _id: 58343076b80874142848f26e }
here is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Meetup = new Schema({
name: String,
});
module.exports = mongoose.model('Meetup', Meetup);
If req.body is undefined (as you wrote in the comments) then obviously new Meetup(req.body); cannot populate the new objects with any data (like {name: 'Text input'} or anything else) since it is called with undefined as an argument.
Make sure you use the body-parser and that you pass the correct data in your request.
Also, check for errors. Every callback that takes the err argument should be in the form of:
module.exports.list = function (req, res) {
Meetup.find({}, function (err, results) {
if (err) {
// handle error
} else {
// handle success
}
});
}
How to track the problem:
make sure you use the body-parser on the backend
make sure you pass the correct data on the frontend
make sure that the data passed by your frontend is in the correct place (body)
make sure that the data is in the correct format (JSON? URL-encoded?)
add console.log(req.body) after new Meetup(req.body); to know what you save
open the Network tab in the developer console of your browser and see what is transferred
I am building my first express.js application and I have run into my first hurdle.
I have a very simple set up.
routes in app.js:
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/products', product.all);
app.post('/products', product.create);
route(controller) in routes/product.js
var Product = require('../models/product.js');
exports.create = function(req, res) {
new Product({ name: req.query.name, description: req.query.description }).save();
};
exports.all = function(req, res) {
Product.find(function(err, threads) {
if (err) {
res.send('There was an error: ' + err)
}
else {
res.send(threads)
}
});
}
Product model in models/product.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var productSchema = new Schema({
name: String,
description: String
});
module.exports = mongoose.model('Product', productSchema);
I have tried sending post requests with both Postman (chrome extension) as well as Curl. I have noticed that both seem to hang after sending the request, as if waiting for a response, i'm no http expert but I assumed a post would not have a response? But perhaps it responds with whether it was successful or not?
my sample requests:
http://0.0.0.0:3000/products?name=Cool, http://0.0.0.0:3000/products?name=Cool%Product&description=Allo%there%Soldier!
After sending the post and then sending a get request to http://0.0.0.0:3000/products I get an array of objects like so:
{
"_id": "52e8fe40b2b3976033ae1095",
"__v": 0
},
{
"_id": "52e8fe81b2b3976033ae1096",
"__v": 0
},
These are equal to the number of post requests I have sent, indicating to me that the server is receiving the post and creating the document/file, but not actually passing the parameters in.
Some help here would be excellent!
EDIT: It seems the code above is fine, I think I may have forgotten to restart my node server after having made some changes (Doh!), the restart fixed the issue
there is something like an http-request lifecycle, and of course an post has a response.
probably something like a 200 if your insert worked and a 404 if not!
you need to send a response in your create method:
exports.create = function(req, res) {
new Product({ name: req.query.name, description: req.query.description }).save();
res.send('saved');
};
Your post needs a response. You could do something like
var newProduct = new Product({ name: req.query.name, description: req.query.description });
newProduct.save(function(err, entry) {
if(err) {
console.log(err);
res.send(500, { error: err.toString()});
}
else {
console.log('New product has been posted.');
res.send(JSON.stringify(entry));
}
});