Mongoose.updateOne() not updating the value in a db - node.js

I am new to nodejs. Mongoose.updateOne is not saving value into db. when i run this, it prints image uploaded in a console but it's not reflecting in a mongodb. I want to update my photo in a db
var a = new photo();
a.img.data = req.files.image.data
a.img.contentType = req.files.image.mimetype;
a._id = req.params.id;
Here is my updateOne method
a.updateOne({_id:req.params.id}, function (err, result) {
if (err){
console.log(err)
}else{
res.send({ status: 1 })
console.log("image uploaded"+result)
}
});

Update: I failed to pass update syntax, and instead of using modelname (photo) i used variable name 'a'. Here it works
photo.updateOne({_id:req.params.id},{img:{data:req.files.image.data,contentType:req.files.image.mimetype}},function (err, result) {
if (err){
console.log(err)
}else{
res.send({ status: 1 })
console.log("image uploaded"+result)
}
});

Related

Delete particular data in mongodb using node js

How can I delete particular data in mongodb using node.js ?
router.post('/deletedata', (req, res) => {
console.log("deleted values are",req.body.id)
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mohan");
var myquery = req.body.id;
console.log("myquery value is:", myquery)
dbo.collection("customers").remove({myquery}, function(err, obj) {
if (err) throw err;
db.close();
});
});
res.json({
statusCode: 200,
result: "success",
})
}
);
export default router;
I got particular id from React hooks crud app , So i can see the id in node js but it does not delete the that particular id data in mongoDB
Your query will only delete documents with myquery: passedId
I bet query should look like {_id: myquery}
dbo.collection("customers").remove({_id: myquery}, function(err, obj) {
if (err) throw err;
db.close();
});
dbo.collection("customers").remove(myquery, function(err, obj) {
if (err) throw err;
db.close();
});
try using delete({query}) or deleteMany({query})

Finish execution if first query returns a value Node.js Express.js mongoDB

Before starting, please mind that i have been searching this over 2+ hours, the answer will be simple i know but i couldnt get it to work . i am new to express node mongodb,
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("EXISTS");
//I WOULD LIKE TO EXIT IF THIS LINE EXECUTES
}
}
});
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("CREATED 201");
} else {
res.send("Failed to insert");
}
}
});
db.close();
});
my goal is to check if an user doesnt exists with given username, i would like to insert that to the DB.
i would like to exit if my query finds an match and arrange such that insertOne wont execute. please enlighten me!!
Once you are not using the async/await syntax you will have to nest the calls to MongoDB, so they execute in series. You can also use a module like async to achieve this.
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
if (result) {
db.close();
return res.send("EXISTS");
}
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
db.close();
if (result) {
return res.send("CREATED 201");
}
res.send("Failed to insert");
});
});
});
Try this
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
//put the error logic
}
else {
if (result) {
//Send the response
return result;
}
else{
// if above if block fails it means that user does not exist
//put the insert logic
}
});

How to find a record and insert the same record in Mongoose?

Here I want to get a record and I need to insert the same record with slight modification. But I can't see the data in my new record which I found in my get record. Here is what I tried, can anyone help me? I think the problem is with this line var institution = new Institution(data);:
Institution.find({_id:i._id}).exec(function (err, result) {
if(result)
transferData(result);
}
});
});
}
function transferData(data){
var institution = new Institution(data);
institution.name = 'xxxx';
institution.save(function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
});
}
find() returns an array of docs that match the criteria in the callback hence the line
var institution = new Institution(data);
will not work as it's expecting a Document not an array.
You could use findById() method as:
Institution.findById(i._id).exec(function (err, result) {
if (result) transferData(result);
});
function transferData(data) {
var institution = new Institution(data);
institution.name = 'xxxx';
institution.save(function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
});
}
A much better approach would involve the findByIdAndUpdate() method:
Institution.findByIdAndUpdate(i._id, {name: 'xxxx'}, {upsert: true}, function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
);

Return data from mongoDB nested queries

What is the method to return data from nested queries.
Im merging multiple function calls into one single module ,
I have the following code
retrieveStudentSessions: function(req, res, callback){
MongoClient.connect(config.mongoPath+config.dbName, function(err, db) {
if(err){
return callback(new Error("Unable to Connect to DB"));
}
var collection = db.collection(config.userList);
var sessionCollection = db.collection(config.session);
var templateCollection = db.collection(config.template);
var tempSession = {session:[], templates:[]};
//Obtain UserID
collection.find({'email' : req.user['_json'].email}).nextObject(function(err, doc) {
if(err){
return callback(new Error("Error finding user in DB"));
}
//Search Session collection for userID
sessionCollection.find({ $or : [{'studentsB' : doc['userid']},{'studentsA' : doc['userid']}]}).each(function(err, doc) {
if(err){
return callback(new Error("Error finding user in DB"));
}
//Update JSON
tempSession.session.push(doc);
//Query for Template Title using Template ID from Session Collection
templateCollection.find({'_id' : doc['templateId']}).nextObject(function(err, doc){
if(err){
return callback(new Error("Error finding user in DB"));
}
//Update JSON
tempSession.templates.push(doc);
});
});
return callback(null, tempSession);
});
});
}
Caller Function
dbCall.retrieveStudentSessions(req, res, function(err, result){
if(err){
console.log(err);
return;
}
console.log(result);
});
Above code returns error undefined is not a function when i try to return variable tempSession. The same works fine with single queries . Is there any specific method of return, when it comes to nested queries?

Unable to retrieve value from PouchDB

After inserting data using PouchDB I tried db.getAll() to retrieve all the documents and db.get() for single documents but none of the objects returned contained the value I was inserted in.
What am I doing wrong?
new Pouch('idb://test', function(err, db) {
doc = {
test : 'foo',
value : 'bar'
}
db.post(doc, function(err, data) {
if (err) console.error(err)
else console.log(data)
})
db.allDocs(function(err, data) {
if (err) console.error(err)
else console.log(data)
})
})
Your allDocs query is running before you have completed inserting the data into PouchDB, due to the IndexedDB API all database queries are asynchronous (they likely would have to be anyway as it's also a HTTP client).
new Pouch('idb://test', function(err, db) {
var doc = {
test : 'foo',
value : 'bar'
};
db.post(doc, function(err, data){
if (err) {
return console.error(err);
}
db.allDocs(function(err, data){
if (err) console.err(err)
else console.log(data)
});
});
});
... should work.

Resources