Error updating mongoDB document using Postman - mongodb

I am trying to update a record from mongoDB collection using Postman.
This is the code I am using to do it.
// Update message with id (using a PUT at http://localhost:8080/messages/:message_id)
router.route('/messages/:message_id')
.put(function(req, res) {
Message.findById(req.params.message_id, function(err, message) {
if (err)
res.send(err);
// Update the message text
message.text = req.body.text;
message.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Message successfully updated!' });
});
});
});
//Updating A Message end.
Next, this is the URI I am typing in Postman to update (based on the id key):
localhost:8080/messages/ObjectId("58ab37f9d23f991791490963")
Then I get this error message:
I am trying to commit to a Bitbucket repository.
What should I change in the URI to make the update valid?

You may want to drop the ObjectId part from what you are posting and just send the id itself then create an ObjectId on the server
localhost:8080/messages/58ab37f9d23f991791490963
router.route('/messages/:message_id')
.put(function(req, res) {
var id = new ObjectId(req.params.message_id)
Message.findById(id, function(err, message) {
...
})

Related

Unable to get the id of newly created record sails js

I am creating a new record like this:
Resource.create({
title: req.body.title,
address: {...req.body.address},
email: req.body.email,
}, (err, record) =>{
if(err){
res.send({'status': err});
}else{
res.send(
{
'status': 'it worked',
'data': req.body
}
);
sails.log(record.title)
}
});
The request process perfectly and the new record is added to the database(I can see it too). But I cant get the id right when its created for some weird reason.
I've been following a tutorial and record is supposed to not be undefined, I am using MongoDB with SailsJS
You have to chain a "fetch" after creating the record, for example:
let resource = Resource.create({...}).fetch();
This will fetch the record you just created with its associated id.

I want my Dialogflow bot to say a message which includes the result from a MongoDB query

I am querying a collection in MongoDB from Dialoglow Fulfillment. I then want my bot to respond with a message which includes this query. The code in the function of the Dialogflow Fulfillment is:
function readRecord(agent){
var name;
MongoClient.connect(uri, function(err, client) {
const collection = client.db("test").collection("data");
collection.find({fname: 'Example'}).toArray(function(err, result){
if (err) throw err;
console.log(result);
name = result.lname;
agent.add("Found last name: ", name);
});
client.close();
});
}
When I run this I get no response from my from the bot. When I console.log(result) the information is there but I can't seem to get the bot to say it.
The issue is that the intent handler expects you to return a Promise if you are doing any asynchronous functions - like accessing a database. The easiest way to do this is to change from using callbacks with MongoDB to using versions of the functions that return Promises, and then to return the promise.
I haven't tested, but something like this might work
return MongoClient.connect( uri )
.then( client => {
const collection = client.db("test").collection("data");
return collection.find({fname: 'Example'}).toArray();
})
.then( result => {
let name = result[0].lname;
agent.add("Found last name: "+name);
});

Why is JQuery casting a string to _id for Mongodb in this? (Please read EDIT)

I have a route that adds an image (a meme) like this:
// add new image by URL
app.post('/api/addMeme', function (req, res) {
var meme = new Meme({
title: req.body.title.trim().toLowerCase(),
image: req.body.image,
meta: {
votes: 0,
favs: 0
},
related: []
});
// Save meme to database
meme.save(function (err) {
if (err) throw err;
Meme.find({}, function (err, meme) {
if (err) throw err;
io.emit('new meme', meme);
});
res.send('Succesfully inserted meme.');
});
});
It takes the only two attribute title and image given by client side ajax and add it to my Mongodb database named Meme. Emit the updated database using socket.io. Both title and image are String type. image is suppose to be an URL to an image.
Now, I'm not ashamed to admit it, but my friend trolled my site and sent image = "www.pornhub.com" to this route and it crashed my database/site. Whenever I go and try to retrieve the image by its _id, I get the error:
CastError: Cast to ObjectId failed for value "www.pornhub.com" at path "_id" for model "meme"
EDIT: it looks like the error is actually coming from the route
app.post('/api/vote', function(req, res){
Meme.findOneAndUpdate({_id: req.body.id}, {$inc : {'meta.votes' : 1}}, {new: true}, function (err, meme) {
if (err) throw err;
if (!meme) return res.send('No meme found with that ID.');
io.emit('new vote', meme);
res.send('Succesfully voted meme.');
});
});
where a POST request is updating the database, and there's a cast error where the _id is given as a string?
The client side script that's doing this is
$("#vote").click(function(){
$.ajax({
type: "POST",
url: '/api/vote',
data: {
id: App.meme._id
},
success: function (data, status) {
console.log(data);
}
});
return false;
});
where App is a Express-state exposed data for which meme, the database, lives under.
But this error ONLY occurs on the object with image = "www.pornhub.com". My guess is that somewhere in the HTML, a cross-site href is visiting www.pornhub.com and somehow App is getting distorted? It doesn't fully make sense why id: App.meme._id would give www.pornhub.com as its value.

Post TypeScript Object without '_id' field?

I use Express, Mongoose and Angular 2 (TypeScript) making an web app. Now I want to post a MyClass Instance without any _id field.
In mongoose we could use _id to do a lot of operations on mongoDB, so here is what I have done on the server side using mongoose
router.post('/', function(req, res, next) {
Package.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /package/id */
router.get('/:id', function(req, res, next) {
Package.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /package/:id */
router.put('/:id', function(req, res, next) {
Package.findByIdAndUpdate(req.params.id, req.body, function (err, post, after) {
if (err) return next(err);
res.json(post);
});
});
To contain the field _id I created a ts Class like this:
export class Package{
constructor(
public guid: string,
...
[other fields]
...
public _id: string
){}
}
Please note the _id at the end.
In my angular 2 service I am doing this to post the json object to server
//create new pakcage
private post(pck: Package): Promise<Package> {
let headers = new Headers({
'Content-Type': 'application/json'
});
return this.http
.post(this.packageUrl, JSON.stringify(pck), { headers: headers })
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
Then I received an error as shown in the screenshot below:
In which it indicates that the object I post back got a empty _id field.
How do I post a ts class without the _id field or should I do it totally differently?
Since no one has given an answer I went to the internet and found a good example of how to implement a Angular2 -- Mongoose -- Express System.
https://github.com/moizKachwala/Angular2-express-mongoose-gulp-node-typescript
A very good example with the original Hero App from official tutorial. Although it is based on RC1 but it provides a good start point on how to do the RESTFUL Request properly.
Hope this would help someone who is looking for a similar answer.

Update MongoDB object field with _assign/_merge/_extend

I am running into a question when to use which one, the following is update function for mongoose, it works fine.
// Updates an existing form in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Form.findById(req.params.id, function (err, form) {
if (err) { return handleError(res, err); }
if(!form) { return res.send(404); }
var updated = _.assign(form, req.body);
updated.formContent = req.body.formContent;
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, form);
});
});
};
Tried the following to replace the form data.
_.assign(form, req.body); // Works (update database)
_.merge(form, req.body); // Not Work (database not updating, remain the same)
_.extend(form, req.body); // Works (update database)
The above result show merge doesn't work when there is object within the post data.
Could some please explain why one is not working the others is ok. I have read the following question
Lodash - difference between .extend() / .assign() and .merge()
but i am curious to understanding which one won't update the database, but when applied with assign and extend it's working.