Cannot update field when located by object id, json parse error - javascript

I have a collection with content:
db.simplecollection2.find()
{ "_id" : ObjectId("5c312200508c979b46d21866"), "artistname" : "The
Tea Party" }
When I change artistname with the following in mongo shell it works
db.simplecollection2.update(
{"_id":ObjectId("5c312200508c979b46d21866")},{"artistname":"new"})
However in javascript I get an Error: SyntaxError: Unexpected token O in JSON at position 7 at JSON.parse (), although I parse a string to object and not object to object.. why is that?
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("simpledb");
var myquery = JSON.parse("{\"_id\":ObjectId(\"5c31184bdb14729aa4806882\")}");
var newvalues = { $set: {"artistname":"cool"} };
dbo.collection("simplecollection2").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});

Update using ObjectID():
let id = new mongo.ObjectID("5c312200508c979b46d21866");
db.simplecollection2.update({ "_id" : id }, { "artistname" : "new" });
Read More

The line where you call JSON.parse fails because the argument is not a JSON. If you do JSON.stringify({"_id":ObjectId("5c312200508c979b46d21866")}) you'll see that it can't turn that into a string either. The reason being that JSONs can contain strings, booleans, numbers, and arrays. ObjectId("5c312200508c979b46d21866") doesn't resolve to something the browser knows, even though it makes sense in the shell. However, I think if you pass it as a string, it should work as a query for the db.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("simpledb");
var myqueryObj = {
_id: 'ObjectId("5c312200508c979b46d21866")'
};
var myquery = JSON.parse(JSON.stringify(myqueryObj));
var newvalues = { $set: {"artistname":"cool"} };
dbo.collection("simplecollection2").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});

Related

Deleting documents with just by first property

I'm attempting to remove documents from MongoDB by the first property in the object. How would I define the myquery variable? req.body.photon.id contains the string of the documents I want to remove.
app.post('/deletephoton',function deletePhoton(req,res){
console.log(req.body.photon.id)
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = req.body.photon.id;
dbo.collection("probes").deleteMany(myquery, function(err,obj)
{
if (err) throw err;
console.log(obj.result.n + " document(s) deleted");
db.close();
});
});
})
Data
{"35002f000f47363333343437":"photon1,0,1546529824,1546529824,5419571,1.151750,1.308505,0.880203,86.42,66.05,75.04,4321.222168,346.858582,14135.343750,39.50C,103.10F,0,0,0,0,0,0,0,9,0,5,0,226,62,0,654","published":"2019-01-03T15:37:14.861Z"},{"330045000f47363336383437":"Photon4,0,1546529881,1546529881,657931,0.948100,1.376440,0.688806,76.88,55.85,81.08,24463.919922,307.444458,5717.383789,37.50C,99.50F,0,0,0,0,0,0,0,27,0,38,0,472,141,0,65","published":"2019-01-03T15:38:16.974Z"},{"35002f000f47363333343437":"photon1,0,1546529901,1546529901,5496166,1.153366,1.309739,0.880608,86.47,66.02,74.98,4319.191895,346.464661,14046.888672,39.00C,102.20F,0,0,0,0,0,0,0,48,0,44,0,21,92,0,65","published":"2019-01-03T15:38:21.356Z"},{"330045000f47363336383437":"Photon4,0,1546529986,1546529986,763657,0.945928,1.375544,0.687676,76.78,55.82,81.17,26526.273438,330.111115,5860.575684,38.00C,100.40F,0,0,0,0,0,0,0,11,0,31,0,139,465,0,6","published":"2019-01-03T15:40:17.786Z"},{"35002f000f47363333343437":"photon1,0,1546529977,1546529977,5572760,1.148823,1.306892,0.879050,86.31,66.04,75.13,4322.939453,346.565643,14356.383789,39.50C,103.10F,0,0,0,0,0,0,0,35,0,25,0,371,101,0,","published":"2019-01-03T15:40:23.340Z"}]
So the way I ended up solving this was to define var myquery = {[req.body.photon.id]: /^/ };

MongoDB object isn't deleted from database

I'm trying to delete something from my mongoDb database based on the _id. In my console I keep getting the message that the row was deleting but when I check the database, the object still exists.
this is my function :
function deleteById(){
//5989df87e027c737e5500d17
url_database= mongodb://localhost:27017/incept
MongoClient.connect(url_database, function(err, db) {
if (err) throw err;
var myquery = { _id: '5989df87e027c737e5500d17' };
db.collection("medicament").removeOne(myquery, function(err, obj) {
if (err){
console.log("failed");
throw err;
}
console.log("1 document deleted");
db.close();
});
});
}
This is my json object
{ _id: 5989df87e027c737e5500d17,
medicine_name: 'ada',
dosage_value: 'ads',
dosage_unit: 'MG',
prescribed_for_days: 'ads',
doctor_name: 'asda',
morning_select: '06:00',
afternoon_select: '06:00',
evening_select: '06:00',
night_selct: '06:00' }
Are you sure about the method removeOne. I think to delete you have to use deleteOne.
deleteOne
You need to convert your string _id value into an ObjectID as that's how it's stored in the collection:
const mongodb = require('mongodb');
var myquery = { _id: mongodb.ObjectID('5989df87e027c737e5500d17') };

mongoDB node.js findAndModify troubles

I am doing an online course about MongoDB which is unfortunately a little out of date. It seems some of the functions have changed (course is using version 1.4 while I am using 3.0.)
Here is the code I am having trouble with, which I have tried to bring up to date with the current version of MongoDB:
app.js
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/course', function(err, db) {
if (err) throw err;
db.collection['counters'].findAndModify({
query: {
name: 'comments'
},
update: {
$inc: {
counter: 1
}
},
new: true
}, function(err, doc) {
if (err) throw err;
if (!doc) {
console.dir('No counter found for comments.');
} else {
console.dir('Number of comments: ' + doc.counter);
}
return db.close();
});
});
If I run the same findAndModify through the Mongo shell I get the anticipated result (increment the counter and display the new document,) but when I run this with node it has no effect on the database and throws this error:
TypeError: Cannot call method 'findAndModify' of undefined
Any tips?
Please try:
db.counters('counters').findAndModify
instead of:
db.collection['counters'].findAndModify
use this now:
db.collection('counters').findOneAndUpdate(
{name: 'comments'}, //query
{$inc: {counter: 1}}, //update
{ //options
upsert: true, // create the doc when it's not there
returnOriginal:false // return the modified doc *(new is not supported here!)
},
function(err, r){ //callback
if(err) throw err;
console.log('counter: '+r.value.counter);
}
);
Whoops, I just had the wrong kind of brackets. Should have had:
db.collection('counters')
instead of
db.collection['counters']
Almost like T_G said.
From the mongodb docs:
Existing collections can be opened with collection
db.collection([[name[, options]], callback);
If strict mode is off, then a new collection is created if not already
present.
So you need to do this:
db.collection('counters', function(err, collection){
collection.findAndModify({
query: {
name: 'comments'
},
update: {
$inc: {
counter: 1
}
},
new: true
}, function(err, doc) {
if (err) throw err;
if (!doc) {
console.dir('No counter found for comments.');
} else {
console.dir('Number of comments: ' + doc.counter);
}
});
});

Can't list documents in mongodb collection using MongoClient in node.js

I can connect to my database from node.js using the MongoClient. I amb able to write, update and remove docs from a collection. But I am not able to retrieve data from it. This is my code:
var mongoClient=require('mongodb').MongoClient;
var mongoDbObj;
mongoClient.connect('mongodb://127.0.0.1:27017/trendoa', function(err, db){
if(err){
console.log(err);
}else{
global.db = db;
};
var col = global.db.collection('twitter_accounts_mon');
// create
var doc1 = {'hola':'sushi'};
col.insert(doc1, function(err, result) {
callback(err);
});
// update
col.update({hola:'jordi'}, {$set:{hola:'joan'}}, {w:1}, function(err, result) {});
// delete
col.remove({hola:'jordi'}, function(err, result) {
callback(err);
});
// read
col.find().toArray(function(err, docs) {
console.log(docs);
});
What I'm trying to do in the last lines of code is to get all the documents using find() but it doesn't return any results.
Through the mongo shell, using this command I get data on screen:
db.twitter_accounts_mon.find()
I don't know what I'm doing wrong. Thanks!
the nodejs callbacks must nest, ie only search the collection once the db is open
mongoClient.connect('mongodb://127.0.0.1:27017/trendoa', function(err, db){
var col = db.collection('twitter_accounts_mon');
coll.find({}, function(err, cursor) {
cursor.toArray(function(err, data) {
// process the data array
}
}
}
According to the MongoDB documentation on the Node.js driver, the find method does not execute the actual query, it builds an instance of a cursor that you then use to retrieve data. thus, you need to handle the result of the query.
var entireCollectionArray = col.find().toArray(function(err, items) {});
entireCollectionArray.forEach(function (element) {
console.log(element);
});

Writing MongoDB result to file using native Node.js driver

I am trying to write the results of a MongoDB query to a file using the native Node.js driver. My code is the following (based on this post: Writing files in Node.js):
var query = require('./queries.js');
var fs = require('fs');
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
if(err) { return console.dir(err); }
var buildsColl = db.collection('blah');
collection.aggregate(query.test, function(err, result) {
var JSONResult = JSON.stringify(result);
//console.log(JSONResult);
fs.writeFile("test.json", JSONResult, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
collection.aggregate(query.next, function(err, result) {
var JSONResult = JSON.stringify(result);
//console.log(JSONResult);
db.close();
});
});
The file is written, but the contents are 'undefined.' Printing the result to the console works though.
Your code is not checking the err on the aggregate callback.
You are likely getting an Mongo error and the result is undefined in that case...
Other thing I could suspect is that you are getting multiple callbacks -- each one of them creates a new files, erasing the content.
Try using fs.appendFile instead of fs.writeFile and see if you are getting the expected data (plus the unwanted undefined)
For anyone stumbling across this the solution on where to put the db.close() is below:
collection.aggregate(query.test, function(err, result) {
var JSONResult = JSON.stringify(result);
//console.log(JSONResult);
fs.writeFile("test.json", JSONResult, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
collection.aggregate(query.next, function(err, result) {
var JSONResult = JSON.stringify(result);
//console.log(JSONResult);
db.close();
});
});

Categories

Resources