Nodejs Mongoose Cannot update values in DB - javascript

I am pretty new to Nodejs and MongoDB. This might be a simple error, but I cannot seem to update values from DB. I searched far and wide but my syntax is seem to be right. Please help me.
var dataConstruct = {}
dataConstruct[fieldName] = fieldValue;
updateRecordModel.find(dataConstruct , function(err, field) {
if(err) {
logger.error("Error deleting records. Error -" + err)
callback(err, "Error while searching for record.Please cheack the values posted")
}
else {
logger.info("JSON"+JSON.stringify(field[0].Option1));
field[0].Option1="Max";
logger.info("JSON"+JSON.stringify(field[0].Option1));
if(field){
//code to update
}
else{
callback(err, "No such data present")
}
}
}).lean();
Find is returning data . I am using .lean() to get javascript object instead of document model object so that I can modify data. I cannot seem to modify the data returned without using .lean() as is the problem in this post Why can't you modify the data returned by a Mongoose Query (ex: findById)
I tried to find the data and update or resave it, I tried all the update syntax and methods(including find and then save doc again) mentioned in this post https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications but none seem to work,as I cannot modify the data returned
This is the json returned from find
{"_id":"564c29d96bf38ba3039f4844","Option1":"Gary","Option2":"Fred","__v":0}
I need to know how to update this value
This is the code I used for findoneand update
updateRecordModel.findOneAndUpdate({"Option1": "Gary" }, { "Option1": "Max" }, function(err,records) {
if (err) throw err;
console.log(records);
});
In console record is being returned without being updated

You can try after field[0].Option1="Max"; use save method. field[0].save() . I hope it help

Since mongoose 4.0 the returned value by the findOneAndUpdate is always the old document. If you want the new one to be returned (the updated document) you have to pass {new: true} in the options, as stated in their documentation.
You should end up with something like this:
updateRecordModel.findOneAndUpdate({"Option1": "Gary" }, { "Option1": "Max" }, {new: true}, function(err,records) {
if (err) throw err;
console.log(records);
});

Related

Complex Mongoose findOneAndUpdate query not working looking for specific advice

I have a somewhat complex Mongoose query I want to make and while I can find the different parts around the internet (including here) I can't seem to find exactly what I need and piecing the existing info together has not worked so I am looking for specific how to do this.
I want to findOneAndUpdate to add data to blockSection array in my document.
Block.findOneAndUpdate({
section: {$elemMatch: {section_code: sectionID}}
},
{"$push": {blockSection.section: blocSecData}}, // blocSecData is defined elsewhere and is an object
(err, result) => {
if(err) {
return res.json({success: false, err})
}
... // more code here to processstuff
})
Rough example of a sample Block with only one item per array
{
"section_code":"<abc>",
"blockSection": [
{
section: [{"text":"hello world"}], // add the data here
"_id":"<foobar>",
"blockSecID":"<a uuid>"
}
]
}

How to insert json object inside nested object in a document based on nested object UUID

I am working on a small project and I am stuck from last month and looking for an exact query to update my document at the exact location...I did my best but didn't get my goal....Please help.
My Current Query
await test.update(
{
"subtests.uuid": req.query.sub_uuid
},
{
$set: {
$push:
{
"subtests.$[element].subtests": req.body
}
}
},
{
arrayFilters: [
{
"element.uuid": req.query.sub_uuid
}
]
});
With this query, I am getting an error saying (Typeerror: Callback.apply is not a function)
MongoDb Document Image
Error
Thank You to everyone who holds my hand in this complex query (for me it very complex because I am trying to solve it from the month)

Mysteriously Invalid Mongoose Query

I'm getting stuck on a stubborn bug in my MEPN app.
This pseudo-code is supposed to assemble a Mongoose query from the options submitted in a user form, and then search a collection using that query.
var query = [];
query.push("{name:"+req.body.name+"}");
query.push("{status:{$in:["+req.body.statusarray+"]}}");
query.push("{range:{$gte:"+req.body.min+",$lte:"+req.body.max+"}}");
Collection.find(query, function(error, cursor){
if(error) console.log("ERROR: "+error);
else //do something
})
Instead, it's printing ERROR: ObjectParameterError: Parameter "filter" to find() must be an object, got {name: 'foobar'},{status : {$in : ['1','2','3']}},{range: {$gte:'0',$lte:'100'}}
Using Collection.find(JSON.parse(query), ...)} instead results in SyntaxError: Unexpected token n in JSON at position 1
Then if I encase the query in { } brackets before passing it to JSON.parse(), it prints Unexpected token { in JSON at position 1
Is there something wrong with the way I am constructing this query?
Collection.find() wants an Object, but you are passing it an array of strings, which is why you're getting that error.
You can make an object a lot of ways, but the simplest is to just make an object literal:
var query = {
name: req.body.name,
status: {$in:req.body.statusarray},
range: {$gte: req.body.min, $lte:req.body.max }
}

How to search mongodb collection entry attributes

I have a collection in my mongo database by the name "user collection". The collection holds entries with one attribute by the name "DBinstaID".
{ "_id" : ObjectId("5595f6be3eaf90ae2d759cc6"), "DBinstaID" : "280430135" }
I am trying to determine whether a new entry has the same DBinstaID value, and if so increase the count of "idCount". The following code is used in my index.js routing file for node.js/express.
var collection = db.get('usercollection');
var checkDuplicate = collection.find({$where: function(){this.DBinstaID === instaID}});
console.log("DUPLICATE STATUS: " + checkDuplicate);
if(!(checkDuplicate)){
idCount++;
}
However, the checkDuplicate variable is simply set to [object Object] instead of the boolean true or false. How can I search the collection and return a boolean?
Thank you in advance for the help.
The collection.find() method is asynchronous, this means you can't get the results right away, and you need to handle anything dependant on these results directly in the callback.
I strongly advise you to have a good read of mongoosejs's docs (at least the code examples), and to take a look at basics of asynchronous programming in node.js (a google search away).
You can use collection.findOne() to get only one result :
var collection = db.get('usercollection');
collection.findOne({DBinstaID: instaID}, function(err, user) {
// don't forget to check for errors here, masked for clarity
console.log("DUPLICATE STATUS: ", user);
if(user) {
idCount++;
}
// rest of the code
});

A Simple Way To Edit And Delete files in a directory in Node.js?

Hello I'm creating a simple blog using express.js, using a data.json file to create/update/delete, posts based on the id.
And every time I do that, I use fs.writeFile to create and update markdown posts using the slug data in the json array.
So when I create a post named First Post, I get a first-post.md file on my /path folder.
The Problem: Every time I'm updating a file and use fs.writeFile I'm creating a new file path without deleting the old one?
Example:
Updating the name data on the json array:
first post
to
first post update
I get a markdown file first-post-update.md.But the old first-post.md file still exists.
Is it possible to delete every markdown file on a directory path that doesn´t have a corresponding link to each slug data in the data.json file?
Something like this:
function deleteFiles(files, callback){
files.forEach(function(filepath){
//Filter every item.id on data.json and get the slug params.
fs.unlink(filepath, function(err) {
//If any markdown file don´t have a corresponding link to each slug data delete them.
});
}
data.json example:
{
"posts": [
{
"name": "First Post",
"desc": "Some description",
"slug": "first-post",
"id": "07cbc3854-7fa7-4451-883c-a9c8c87143ef"
}
]
}
some example code to create and update posts:
exports.save = function (req, res) {
var slugTitle = slug(req.body.name).toLowerCase().split('.').join("");
var description = req.body.desc;
db.add({name:req.body.name, desc:req.body.desc, slug: slugTitle});
fs.writeFile("path/"+slugTitle+".md", description, function(err) {
if(err) {
console.log(err);
} else {
console.log("The new post was created on path/"+slugTitle+".md");
}
});
res.redirect('/post');
};
exports.update = function (req, res) {
var slugTitle = slug(req.body.name).toLowerCase().split('.').join("");
var description = req.body.desc;
db.update({id: req.body.id, name: req.body.name, desc: req.body.desc,slug: slugTitle});
fs.writeFile("path/"+slugTitle+".md", description, function(err) {
if(err) {
console.log(err);
} else {
console.log("The new post was updated on path/"+slugTitle+".md");
}
});
res.redirect('/post');
};
Have you considered removing the old markdown file as part of the update process? You could retrieve the slugTitle from the document in the database prior to updating it, and then delete that file. I've outlined an example below, you could make this another function or integrate it directly into your update function. You'd want to put some thought into what will work best in your code, without too many layered callbacks.
Note that I'm using findById from Mongoose, but you could apply the concept to whatever system you're using.
db.findById(req.body.id, 'slug', function(err, slugTitle) {
if(err) {
console.log(err);
}
fs.unlink("path/"+slugTitle+".md", function(err) {
if(err) {
console.log(err);
} else {
console.log("Deleted the old markdown file: " + slugTitle +".md");
}
});
});
You may want to look into using a database system like MongoDB or SQL to do this instead. It's usually easier to use a database instead of writing all this stuff yourself. No need to reinvent the wheel, so to speak. It looks like you're already using one to store the meta-data, why not do so for the entire article?
That being said, yes it would seem that your initial code snippet should work.

Categories

Resources