Inserting a variable as a key in MongoDB - node.js

I am retrieving JSON data from an API and this is a short example of it:
{"hatenames":
{"id":6239,
"name":"hatenames",
"stat1":659,
"stat2":30,
"stat3":1414693
}
}
I am trying to insert it in the MongoDB (using MongoClient) but it won't let me put just the object directly or use a variable as a field name. If I put the var username it will just output it as username in the database field. This is what I would like to work:
collection.insert({object}
collection.insert({username:object[username]}
but it doesn't and I've been stuck on this for the past few hours. The only resolution I found was to set it and then update the field name afterwards, but that just seems lame to have to do every single time, is there no elegant or easy option that I am somehow missing?

First of all, being a programmer, you should forget about "it does not work" phrase. You should describe how it does not work with exact error messages you encounter. Not to your problem.
Just because I can easily do
db.coll.insert({"hatenames":
{"id":6239,
"name":"hatenames",
"stat1":659,
"stat2":30,
"stat3":1414693
}
})
or var a = {"hatenames":{"id":6239, "name":"hatenames", "stat1":659, "stat2":30, "stat3":1414693}}; and db.coll.insert(a),
I think that the problem is that your object is not really an object, but a string. So I suspect that you have a string returned to you back from that API. Something like '{"hatenames":{...}' and this caused a problem when you try to save it or access the properties. So try to convert it to JSON.

Try doing this:
MongoClient.connect('mongodb://127.0.0.1:27017/db_name', function(err, db) {
if(err) throw err;
someCollection = db.collection('some_collection');
});
someCollection.insert({
name: hatenames['name']
});
EDIT
For Dynamic approach, I would suggest you to play aroung this function:
Object.keys(hatenames)
this function will return keys in array.
EDIT 2
I have founded a link: Insert json file into mongodb using a variable
See, if that helps.

Related

Mongoose model deleteOne() only works with hard coded string

I have a strange error with mongoose deleteOne() function. Today I wanted to work on my project and got an error while deleting an item from a collection. It simply doesn't delete the document until I use a hardcoded parameter for the options object like this:
const { deletedCount } = await Model.deleteOne({symbol: 'hardcoded'})
// results in deletedCount = 1
But if I try to use a dynamic string like:
const test = 'dynamic'
const { deletedCount } = await Model.deleteOne({symbol: test})
// results in deletedCount = 0
It does no longer delete the document from my collection. The strange thing is yesterday it worked fine and deleted the item.
I tried one other thing I read regarding errors with deleteOne():
const { deletedCount } = await Model.deleteOne({symbol: JSON.stringifiy(symbol)})
But this doesn't work, too.
Does anyone have an idea what's going wrong?
I always default to using ids whenever possible to make sure there's no mistake in the data I am targeting with a given operation.
So in this case that would mean using findByIdAndDelete() instead.
If I don't know the id of the document I'm trying to delete, then only I'd use findOneAndDelete() or deleteOne(), as you have, with something other than an id to identify the document I'm looking for.
Are you certain that the key-value pair you're passing to the function exists in your database?
Problem solved. I accidentally added an additional space character at the end of the string. This is very strange because the error was there since the beginning of my project and yesterday it worked.
So for everyone who might have a similar problem:
I have a ejs template file where I render a html element like this:
<div id="<%= symbol %> ">
Then in my event handler for requesting the server to deleting one item from my list I use the id attribute as a request parameter in the body. In the route handler this parameter is passed to mongoose:
const { symbol } = req.body
const { deletedCount } = await Model.deleteOne({ symbol })
As I mentioned. In the template file after the last ejs seperator there is an addional space character that caused the error. I spotted this issue by making a copy of the monoogse query and than logged it to the console. There I could see the wrong condition parameter.

How to get the id from the given lines of code?

{
acknowledged: true,
insertedId: new ObjectId("612d9d08db9c20f031033478")
}
This was the JSON format I got while I added a file and some other things to MongoDB and I want to get this id separately to save the file to another folder.
Can anyone please explain this?
I believe this question was answered by Vikas in this thread How to get value from specific key in NodeJS JSON [duplicate]
Edited The Answer. Now Its working for above object in question
You can use following function to access the keys of JSON. I have
returned 'mm' key specifically.
function jsonParser(stringValue) {
var string = JSON.stringify(stringValue);
var objectValue = JSON.parse(string);
return objectValue['mm'];
}
if this is a JSON String, at first of all you have to parse it to object liertal, then you can access the specified property you mentioned, so you can do like the following:
function parseJsonString(jsonString) {
// first parse it to object
var obj = JSON.parse(jsonString);
// now access your object property/key
var id = obj.insertedId;
}
If your doing it on mongodb shell or Robo3T then, the line of code would be:
db.collection_name.find({},{insertedId:1})
This is related to projection. 1 represents you want to display it as your output.
In your case as you want only the value of your object id to get displayed, you have to use .valueOf() ; that is ObjectId().valueOf().
-> insertedId: new ObjectId("612d9d08db9c20f031033478")
-> ObjectId("612d9d08db9c20f031033478").valueOf()
->
-> 612d9d08db9c20f031033478
Your can refer this : https://docs.mongodb.com/manual/reference/method/ObjectId.valueOf/ site for your reference.
So you can use this .valueOf() in your code and get the id saved in the document

*ngFor loop over mLab objects produce Error trying to diff'[object Object] even after declaring array

I have an array declared as carousels: any = [] in my TS file but I keep getting an error stating 'only arrays and iterables allowed' whenever I loop over it using *ngFor. The data inside this array is acquired from mLab.
The goal of my code is to update an object from mLab using its id which seems to work fine. But whenever I press the update, given the fact that the update even works, why do I still get the error?
I have tried to change carousels: any = [] to just carousels = [] but it doesn't seem to change anything.
This is my code.
api.js (backend) - this is the code that communicates with the database.
router.route('carousel/update/:_id).put(function(req, res) {
db.collection('home').updateOne({"_id": ObjectId(req.params._id)}, {$set: req.body}, (err, results) => {
if (err) throw err;
res.send(results)
console.log(req.params._id)
});
});
home.service.ts
return this.http.put<any[]>('./api/carousel/update/' + id, {'header': newheader, 'subheader': newsubheader})
}
component.ts
declaration:
carousels: any = [];
update function:
updateSlide(id: number){
this.HomeService.updateSlide(id, this.header, this.subheader).subscribe(slides => {this.carousels = slides})
}
Update works but I still get the Error: error trying to diff '[object object]'. only arrays and iterables are allowed
The .updateOne({}) doesn't return a list of objects, but an object with the information about the row updated.
You are returning that Object from the API and then setting it in the updateSlider() in your component, where you should be setting an array instead.
Try to log the results in the api or slides in the Subscription, and you should be able to see the issue.
After several readings and posts, I have found out that my mistake was tha I manually subscribed to the Observable inside my component file.
Manually updating looks like this:
.subscribe(slides => {this.carousels = slides})
It turns out that this has already been done automatically therefore I would not need to do it again manually. Refer to this post: Pipe Async - Error trying to diff '[object Object]'. Only arrays and iterables are allowed
This fixed the issue for me.

MongoDB update object and remove properties?

I have been searching for hours, but I cannot find anything about this.
Situation:
Backend, existing of NodeJS + Express + Mongoose (+ MongoDB ofcourse).
Frontend retrieves object from the Backend.
Frontend makes some changes (adds/updates/removes some attributes).
Now I use mongoose: PersonModel.findByIdAndUpdate(id, updatedPersonObject);
Result: added properties are added. Updated properties are updated. Removed properties... are still there!
Now I've been searching for an elegant way to solve this, but the best I could come up with is something like:
var properties = Object.keys(PersonModel.schema.paths);
for (var i = 0, len = properties.length; i < len; i++) {
// explicitly remove values that are not in the update
var property = properties[i];
if (typeof(updatedPersonObject[property]) === 'undefined') {
// Mongoose does not like it if I remove the _id property
if (property !== '_id') {
oldPersonDocument[property] = undefined;
}
}
}
oldPersonDocument.save(function() {
PersonModel.findByIdAndUpdate(id, updatedPersonObject);
});
(I did not even include trivial code to fetch the old document).
I have to write this for every Object I want to update. I find it hard to believe that this is the best way to handle this. Any suggestions anyone?
Edit:
Another workaround I found: to unset a value in MongoDB you have to set it to undefined.
If I set this value in the frontend, it is lost in the REST-call. So I set it to null in the frontend, and then in the backend I convert all null-values to undefined.
Still ugly though. There must be a better way.
You could use replaceOne() if you want to know how many documents matched your filter condition and how many were changed (I believe it only changes one document, so this may not be useful to know). Docs: https://mongoosejs.com/docs/api/model.html#model_Model.replaceOne
Or you could use findOneAndReplace if you want to see the document. I don't know if it is the old doc or the new doc that is passed to the callback; the docs say Finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback., but you could test that on your own. Docs: https://mongoosejs.com/docs/api.html#model_Model.findOneAndReplace
So, instead of:
PersonModel.findByIdAndUpdate(id, updatedPersonObject);, you could do:
PersonModel.replaceOne({ _id: id }, updatedPersonObject);
As long as you have all the properties you want on the object you will use to replace the old doc, you should be good to go.
Also really struggling with this but I don't think your solution is too bad. Our setup is frontend -> update function backend -> sanitize users input -> save in db. For the sanitization part, we use a helper function where we integrate your approach.
private static patchModel(dbDocToUpdate: IModel, dataFromUser: Record<string, any>): IModel {
const sanitized = {};
const properties = Object.keys(PersonModel.schema.paths);
for (const key of properties) {
if (key in dbDocToUpdate) {
sanitized[key] = data[key];
}
}
Object.assign(dbDocToUpdate, sanitized);
return dbDocToUpdate;
}
That works smoothly and sets the values to undefined. Hence, they get removed from the document in the db.
The only problem that remains for us is that we wanted to allow partial updates. With that solution that's not possible and you always have to send everything to the backend.
EDIT
Another workaround we found is setting the property to an empty string in the frontend. Mongo then also removes the property in the database

Extjs: Overwrite objects in a record ready to save

Hi guys can anyone shed some light on how to do this please.
I have a userRecord object with various sub-objects in including things like their skills-sets, contracts etc.
I get the record by querying the store for the userId as below.
var userRecord = userStore.findRecord('id', userId);
Next I have a variety of forms with checkboxes in a tabpanel relating to each of the user's sub-objects e.g. Skillsets and Contracts. I am trying to overwrite these on the userRecord with an array on checkboxes that have been checked.
var skillsetCheckBoxes = skillsetPanel.query('checkboxfield[checked=true]');
var skillsets = new Array();
Ext.each(skillsetCheckBoxes, function (skillset)
{
console.log(skillset);
skillsets.push(skillset);
});
I have tried to set the userRecord's engineer's skillset object to be the new array:
userRecord.set(('engineer').skillsets, skillsets);
But when I log the record after doing this it is still the same record I retrieved from findRecord() with no edited fields.
Any help much appreciated,
Thanks!
Hard to say without knowing your model's structure, but your line is clearly wrong. You are using ('engineer').skillsets as the key argument for the set method. Since it's not a string but an array, it won't do anything good.
Your line should rather be something like that:
// You should probably test that there is something in there, or the
// next line could crash...
var engineer = userRecord.get('engineer');
if (engineer) {
userRecord.get('engineer').skillsets = skillsets;
}

Resources