Plain object mongoose not work with sort - javascript

I need plain javascript object instead of mongoose object.
Query
chatModel.find({'userId':userId},{
"_id":0,"message":1,"type":1
}).sort({createdDateISO:-1})
.lean().exec((err,result)=>{
});
But I will get mongoose object when I remove the sort() I am getting the plain javascript object.
How do i get the plain object with sort??

Passing options (in this case return the raw js objects, not mongoose documents by passing lean.So you cant use lean with sort(only use with mongoose document)

Related

Set property in mongoose object after query [duplicate]

This question already has answers here:
Why can't you modify the data returned by a Mongoose Query (ex: findById)
(3 answers)
Closed 3 years ago.
while development of an API, I often need to set extra properties in the result of mongoDb query results. But I can't do it in a good way. For example
Model
const Cat = mongoose.model('Cat', { name: String,age:Number });
Query
Cat.findOne({age:2}) .then(
cat=>{
cat.breed="puppy";
console.log(cat)
} )
here after I get the result from mongoDb I want to set the property of breed to the result , but I can't do it because the property is not defined in the Schema
So to set an extra property I use a hack
cat = JSON.parse(JSON.stringify(cat));
cat.favFood = "Milk"
I don't think its a good way to code. please give a better way of setting property and explain how the hack is working.
Mongoose can actually do the conversion toObject for you with the .lean() option. This is preferred over manual conversion after the query (as willis mentioned) because it optimizes the mongoose query by skipping all the conversion of the raw Mongo document coming from the DB to the Mongoose object, leaving the document as a plain Javascript object. So your query will look something similar to this:
Cat.findOne({age:2}).lean().then(
cat=>{
cat.breed="puppy";
console.log(cat)
}
)
The result will be the same except that this will skip the Mongoose document-to-object conversion middleware. However, note that when you use .lean() you lose all the Mongoose document class methods like .save() or .remove(), so if you need to use any of those after the query, you will need to follow willis answer.
Rather than using JSON.parse and JSON.stringify, you can call toObject to convert cat into a regular javascript object.
Mongoose objects have methods like save and set on them that allow you to easily modify and update the corresponding document in the database. Because of that, they try to disallow adding non-schema properties.
Alternatively, if you are trying to save these values you to the database, you may wish to look into the strict option (which is true by default).

Passing Javascript Object Array to MVC Controller w/ POST

So I have an array of javascript objects that is constructed using JQuery across multiple table rows. It has the following form:
obj_rows = [
{"param1":value11, "param2":value12, "param3":value3},
{"param1":value21, "param2":value22, "param3":value23},
//more objects with the same parameters
]
What I would like is a way for an AJAX POST request to a Controller method SomeController/SomeAction that takes in this array and can iterate over all objects. I was trying to figure out a way to do this using JSON, but to no success.
NOTE: Even though I am using MVC, I do not have a model class corresponding to these objects. Ideally, I would like to end up with some structure like a List of 3 Tuples.
actually the solution is to take the object and stringify it into a string and then send it over the ajax request.
just do:
JSON.stringify(obj_rows)
and you will get on the other endpoint an array (stringified of course), you have to parse it back and you will have your array.
You can use javascript method JSON.stringify() to convert you object into a string and assign its result to a hidden field in your view and once you recieve this in your controller you can then deserialize it to an object or parse it yourself.

Converting the result of a TYPO3 repository query into a JSON object?

Is there a way to convert the result of a "findAll()" on a Repository into a JSON object, change the properties of specific records in Javascript and then return it to the Action and convert it back to be accessed by the Action for persisting it in the DB?
Basically this:
$test= $this->testRepository->findAll();
$testJSON = json_encode($test);
$this->view->assign('testjson', $testJSON);
doesn't work.
$test->toArray()
The collection object (IIRC ObjectStorage) gives you the possibility to use the toArray() method and then encode that

insert an object as identic document into mongo

I have an object that i like to store into mongo. My issue is that i want to store the object's attributes as fields of the document, and not the whole object as a single field.
obj ={attA:x, attB:y} ;
MyCol.insert({obj});
After inserting the object I get this:
{_id:xxxx, obj:{attA, attB}}
Rather I'm looking for this result
{_id:xxx, attA:x, attB:y}
I tried with a JSON.stringify but didn't work. What am i missing?
Do it in this way:
MyCol.insert(obj);
Note, in ES6 creating object using syntax {obj}, is the same as {obj:obj}.

js get elements from array of a serialized form object

Im using JS for a quick web form, all is working fine, I place the responses of the form in a serialized js object into an array,
var myCars = new Array($('#popup-form').serialize());
console.log(myCars);
which gives me on the console:
["name=asfe&email=juan234%40gmail.com&phone=&password=&options=discuss-offer&other=", $family: Object, each: function, clean: function, associate: function, link: function…]
so the question is, this is not behaving like a normal array?
is the array the best way to take the elements?, I tried with mycars[0], but is not working,
Im just coming back to JS!, what is missing to get the elements for the form?, thanks!
jQuery has a serializeArray() method as well.
The .serializeArray() method creates a JavaScript array of objects,
ready to be encoded as a JSON string. It operates on a jQuery object
representing a set of form elements.

Categories

Resources