Resolved, the issue was with the PUT request , I had to specify the header properly and go on with one at a time.
curl -X PUT -H "Accept: application/json" -d "prenom=Maxwell" localhost:3000/contact/51df5cec5e88a2bbce7fac05
I'm trying to modify a mongodb document via coffeescript in a node.js application I'm currently working on and when I try :
curl -X PUT -d '{"nom": "House", "prenom": "Maxwell"}' localhost:3000/contact/51ddb907ae3267d6154a3e64
on this
{
"_id": "51ddb907ae3267d6154a3e64",
"archive": 1,
"nom": "Bir",
"prenom": "Sim"
}
The ID and the routes are correct, so I'm pretty sure the error lies in the javascript logic but I can't seem to grasp the right angle to work it. Here is the defective code :
exports.modifyContact = (req, res) ->
db.collection "data-center", (erreur, collection) ->
collection.update { _id: new mongo.BSONPure.ObjectID(req.params.id) }, { $set: req.body } , (erreur, resultat) ->
res.send resultat
res.end()
and the result is
{
"_id" : ObjectId("51df4ad424f6d9207cc3e2d5"),
"nom" : "Bir",
"nom": "House",
"prenom": "Maxwell" : "",
"prenom" : "Sim"
}
I can't seem to find an effective way to set missing value and modify value already in there. What is wrong ?
Give this a try instead:
exports.modify = (req, res) ->
fields = if (typeof req.body == 'string') then JSON.parse(req.body) else req.body
db.collection "data-center", (erreur, collection) ->
// check erreur here
collection.update { _id: new mongo.BSONPure.ObjectID(req.params.id) }, { $set: fields }, (erreur, resultat) ->
// check erreur here
res.send resultat
res.end()
It is important to note that inserting data directly from req.body without some sort of validation/content checking is not secure and should be avoided (even if it works as expected).
If you want to just "merge" a set of fields into an existing object you do it this way
test:PRIMARY> db.t2.insert({b:1})
test:PRIMARY> db.t2.update({b:1}, {$set: {a:1, c:2}})
test:PRIMARY> db.t2.find({b:1})
{ "_id" : ObjectId("520a3f10e2d66ef50d3b042b"), "a" : 1, "b" : 1, "c" : 2 }
Ah yeah and for the json issue, you cannot use the "original" object to return as json. You need to perform a findOne to retrieve the updated object from mongodb or change to using a findAndModify with the parameter new to get the changed object in a single operation. The existing object might well have have circular references.