Deleting documents with just by first property - javascript

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]: /^/ };

Related

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

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();
});

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') };

Error when deleting from mySQL in node.js

I'm getting an error I don't understand when sending the parameters to my method, I thought my query was wrong but I did it manually and mySQL did what it had to do. So the problem is in my code but I don't seem to find where, thanks in advance.
exports.defav = function(id_user, id_restaurant, callback){
console.log(id_user + " " + id_restaurant); //Just making sure i'm reciving correclt
pool.getConnection(function(err, connection){
if(err){
console.log(err);
callback(true);
return;
}
connection.query("DELETE FROM favorites WHERE id_user = ? AND id_restaurant = ?", id_user, id_restaurant, function(err, results) {
console.log("SUCCESS: Removed from fav ");
connection.release();
if(err){
console.log(err);
callback(true);
return;
}
callback(results);
});
});
};
The error I'm getting is:
throw err; // Rethrow non-MySQL errors
^
TypeError: this._callback.apply is not a function
Query parameters should be passed in an array:
connection.query("DELETE FROM favorites WHERE id_user = ? AND id_restaurant = ?", [ id_user, id_restaurant ], function(err, results) {
...
});

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