Hello I am having issues deleting a document from MongoDb using an object
here is what I mean
const deleteTrimByName = function (db, callback) {
// Get the documents collection
const collection = db.collection(documentName)
// Insert some documents
console.log(trimNameToDelete)
collection.deleteOne({Video_trim: trimNameToDelete}, function (err, result) {
assert.equal(err, null)
assert.equal(1, result.result.n)
console.log('Removed the document')
callback(result)
})
fs.unlink('./public/videos/cut-videos/' + documentName + '/' + trimNameToDelete.trimName + '.mp4', (err) => {
if (err) {
console.log('failed to delete local image:' + err)
} else {
console.log('successfully deleted local image')
}
})
}
where trimNameToDelete evaluates to
{"trimName":"cut2","startTime":"00:00:05","endTime":"00:00:15"}
and the mongo document appears as this in the shell
{ "_id" : ObjectId("5abe67897a9b9e0933c64acd"), "Video_trim" : { "trimName" : "cut2", "startTime" : "00:00:05", "endTime" : "00:00:15" } }
the error I get is
AssertionError [ERR_ASSERTION]: 1 == 0
For technical reasons use the Id cannot be used for deleting.
Ah I found the issue, I needed to parse the trimNametoDelete, stupid mistake, I was sending the trimNametoDelete as a string.
const deleteTrimByName = function (db, callback) {
// Get the documents collection
const collection = db.collection(documentName)
console.log('>>>>>' + trimNameToDelete)
collection.deleteOne({Video_trim: JSON.parse(trimNameToDelete)}, function (err, result) {
assert.equal(err, null)
assert.equal(1, result.result.n)
console.log('Removed the document')
callback(result)
})
fs.unlink('./public/videos/cut-videos/' + documentName + '/' + JSON.parse(trimNameToDelete).trimName + '.mp4', (err) => {
if (err) {
console.log('failed to delete local image:' + err)
} else {
console.log('successfully deleted local image')
}
})
}
Related
I have tried to use the following code to retrieve the Lotus user detail by Node.js.
let ActiveDirectory = require('activedirectory');
let config = {
attributes:{user: ["*"]},
url: 'ldap://mylotusdominoserver',
baseDN: 'OU=myOU,O=myOrg',
}
let ad = new ActiveDirectory(config);
ad.authenticate(user, password, function (err, auth) {
if (err) {
console.log('ERROR0: ' + JSON.stringify(err));
return;
}
if (auth) {
console.log('Authenticated!');
let query = "&(objectClass=*)(CN=Amy*)";
ad.find(query, (err, results) => {
if ((err) || (!results)) {
console.log('ERROR1: ' + err);
return;
}
console.log(results.other[0]);
});
}
else {
console.log('Authentication failed!');
}
});
It returns:
Authenticated!
{
dn: 'CN=Amy Tomson,OU=myOU,O=myOrg',
mail: 'amyt#myOU.myOrg',
sn: 'Amy',
cn: 'Amy Tomson'
objectclass: [Array],
givenname: 'Amy',
uid: 'amyt#myOU.myOrg',
maildomain: 'myOrg'
}
However, the return attributes do not include the working title of the user,
I have added the following attributes to force the server to return all attributes of the user.
attributes:{user: ["*"]},
However, it does not work.
My Lotus Note Domino Server version is 9.0.
Is it possible to fix it?
Finally, I use ldapjs library to fix the problem.
Here is the sample code:
const ldap = require('ldapjs');
var client = ldap.createClient({
url: 'ldap://mylotusdominoserver'
});
client.bind(userName, password, function(err) {
if (err) {
console.log('ERROR0: ' + JSON.stringify(err));
return;
}
});
let opts = {
attributes: ['givenname', 'sn', 'uid'],
filter: '&(title=Manager)(uid=*myOU.myOrg)',
scope: "sub",
}
client.search('OU=myOU,O=myOrg', opts, function(err, search) {
if (err) {
console.log('ERROR1: ' + JSON.stringify(err));
return;
}
let results = [];
search.on('searchEntry', function(entry) {
results.push(entry.object);
});
search.on('end', function(entry) {
console.log("End:" + entry.status);
console.log(results);
client.unbind(function(err) {
console.log("Unbinded.");
if (err) {
console.log('ERROR3: ' + JSON.stringify(err));
return;
}
});
});
search.on('error', error => {
if (error) {
console.log('ERROR2: ' + JSON.stringify(error));
return;
}
});
});
I have a variable deleteFlag which is inaccessible inside a function even though the variable's scope is global.
Explanation (Pls refer my code simultaneously):
Here, I am trying to get a MongoDB collection details, the collection store a date document (result[i].date). The variable difResult stores the difference between the current date and the date fetched from MongoDB. And let's say if the value of difResult is more than a specific threshold then handle respective if-else conditions.
My if block i.e. if(difResult>20000) has a child-process, exec function and a callback function to delete MongoDB collection, now in this function I am trying to access var deleteFlag which is sort inaccessible.
Why? And how can I make is accessible inside my function?
app.js
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
if (err) throw err;
var dbo = db.db("dbName");
dbo.collection("colName").find({}).toArray(function(err, result) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var difResult = Math.round((today - result[i].date));
var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
console.log("Result Date " + result[i].date);
if (difResult > 20000) {
var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
return res1.status(500).json({
error: "Failed!"
});
} else {
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
console.log("Delete Flag From Collection ", +deleteFlag.toISOString());
//The above console log gives NaN or null value
//Suggest that var deleteFlag is not accessible inside this callback function
if (err) throw err;
var dbo = db.db("dbName");
var myquery = {
date: deleteFlag
};
dbo.collection("colName").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
db.close();
});
});
}
});
} else {
console.log("Else msg");
}
}
db.close();
});
});
You don't have to call the database twice you can optimize your code and use it like this
MongoClient.connect("mongodb://localhost:27017/", {
useUnifiedTopology: true
}, function(err, db) {
if (err) throw err;
var dbo = db.db("dbName");
dbo.collection("colName").find({}).toArray(function(err, result) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var difResult = Math.round((today - result[i].date));
var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
console.log("Result Date " + result[i].date);
if (difResult > 20000) {
var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
return res1.status(500).json({
error: "Failed!"
});
} else {
var myquery = {
date: deleteFlag
};
dbo.collection("colName").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
});
}
});
} else {
console.log("Else msg");
}
}
db.close();
});
});
However if for whatever reason you need to call the database twice then store deleteFlag values in an array and then access the array wherever you like
I have made class model for my view the code below (I'm using nw.js ) :
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database('./../data.sqlite');
class store_model{
constructor() {
this.state = {
_stmt: null
}
}
readAll() {
db.each("SELECT * FROM store ", (res, err) => {
if (err)
console.log(err);
else
console.log(res);
});
}
read(obj) {
db.get("SELECT * FROM store WHERE ID =" + obj.id, (res, err) => {
if (err)
console.log(err);
else if (res !== null)
console.log(res);
else
console.log()
});
}
create(obj) {
try {
db.serialize(() => {
this.state._stmt = db.prepare("INSERT INTO store (name,mail) VALUES (?,?)");
this.state._stmt.run(obj.name , obj.mail);
this.state._stmt.finalize();
})
}
catch (err) {
console.log("There is an error " + err);
}
}
update(obj) {
db.serialize(() => {
this.state._stmt = db.prepare("UPDATE store SET name = COALESCE(?, name) , mail=COALESCE(?,mail) WHERE ID=? ");
console.log(obj.name)
try {
this.state._stmt.run(obj.name, obj.mail, obj.id);
}
catch (err){
console.log(err);
}
this.state._stmt.finalize();
console.log("updated ....");
})
}
delete(obj) {
this.state._stmt = db.prepare("DELETE FROM store WHERE ID=?");
this.state._stmt.run(obj.id);
console.log("supprimer");
}
}
After Made it I want to pass the response of some of my requests to my view in vue.js the problem I meet is that my requests are in asynchronous function so I can't pass directly my response to my view object because of the scope .I would like someone guide me ( A way to pass the responses of my requests) to be able to transmit my responses to my view object
(My view object have attribute to receive data) .
I'm creating a new user with POST and the program tells me it's created correctly , but when I check with GET if the user was created , it creates an empty {} entry. What can be wrong here?
app.get(BASE_API_PATH + "/contacts", (req, res) => {
console.log(Date() + " - GET /contacts");
db.find({}).toArray((err, contacts) => {
if (err) {
console.error("Error accesing DB");
res.sendStatus(500);
return;
}
res.send(contacts.map((c) => {
delete c._id;
return c;
}));
});
});
app.post(BASE_API_PATH + "/contacts", (req, res) => {
console.log(Date() + " - POST /contacts");
var contact = req.body;
if (!contact) {
console.log("warning : new Get req");
res.sendStatus(400);
}
db.find({ "name": contact.name }).toArray((err, contacts) => {
if (err) {
console.log("error accesing db");
res.sendStatus(400);
}
if (contacts.length > 0) {
console.log("warning");
res.sendStatus(409);
}
else {
db.insert(contact);
res.sendStatus(201);
}
});
});
So i have implemented a mongodb on my nodejs server. And what I have done is store users via:
function insertUser() {
var collection = dbb.collection('user');
var user1 = {name: user, token: token};
collection.insert(user1, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
}
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.find({name: devName}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found: ', result);
selectedUserToken = result.token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
So result will equal:
Found: [ { _id: 57be1cadc281c03ea116c9ab,
name: 'Austin Hunter',
token: 'dJyXVjMJk08kXWrua8SUjKb....SxACihKZoR53y_wOZmcFNKMmD5q99QNvsp3flL' } ]
My question is, how can I get that token out to equal selectedUserToken so I can send a push notification with gcm? Right now result.token is undefined.
You should use findOne() instead of find() since you only expect a single result back:
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.findOne({name: devName}, function (err, result) {
if (err) {
console.log(err);
} else if (result) {
console.log('Found: ', result);
selectedUserToken = result.token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
But if you wanted to leave your code as is with the find() you would just retrieve the first element of the resulting array retrieved by find()
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.find({name: devName}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found: ', result);
selectedUserToken = result[0].token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
Maybe result[0].token, because result is an array of user items.