Using findOne with Arrays in Mongoose with NodeJS - javascript

in NodeJS with Mongoose, how do i search something in an array using findOne()? I want to search stuff like 626ead978edc5f2a3f7ca924 in the users array in my sessionCollection-Model.
My DB looks like this: Database Picture

It'll work normally as it does for non array key:
SessionCollection.findOne({users: mongoose.Types.ObjectId("626ead978edc5f2a3f7ca924")})
You might need to cast to objectId to get the desired result.
Reference

Related

MongoDB array turned into string on database

I have problem with Mongo/express array parsing. A array from body seems to be correct when I console.log response in node console. But the problem is when I try to save the body to mongo.db using insert.one method, the post is saved but the array turns into string, which is bad for me.
This is what I'm sending to mongo (the data is ok, i console.log it, array is not string here)
{
createdBy: this.userName,
postContent: this.post,
tags: this.tags,
addedAt: new Date()
};
And this is what is stored in database
Update:
When I hardcode array into payload it's showed correctly as an array in mongo.
But of course problem still exist for dynamic data
You should be able to use JSON parse along with a replace to force it to accept the string as an array, like this:
const array = JSON.parse(this.tags.replace(/'/g, '"'));
Then set tags to the value of array:
tags: array
Use data type as array -- 4 and use .pretty().
Generally if you use find() method returns data in a dense format.
By using cursor.pretty() you can set the cursor to return data in a format that is easier for humans to parse

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).

Retrieve data as array of objects || Firebase

Im kinda new in firebase. As a first step, I would like to set a post and get calls to my newly made database in firebase.
Firebase has a lot of native functions which allows me to get elements and push them to the db. However, I would prefer to use native get/post calls.
My post calls seem to work just fine, it properly stores an element in the db and returns 200 status.
When I enter to my DB in firebase, I can see that it posses following data:
entries:
-L1cxn3-rLgp7PsPwjV3
author: "Mark"
title: "Hello"
-L1cyaOQ4TUYd3m16VfT
autor: "Lily"
title: "Hi"
So as I said before, it stores correct data. But the structure is unknown for me. It's like a map or an object.
I would like to ask you for help, how to properly retrieve it from get call.
The get call returns:
{"-L1cxn3-rLgp7PsPwjV3":{"author":"Mark","title":"Hello"},"-L1cyaOQ4TUYd3m16VfT":{"author":"Lily","title":"Hi"}};
I could take all keys from it Object.keys(data)
Then iterate over it to get it as an array -
Object.keys(data).map(r => data[r])
Now I would have an array of objects.
Is it a proper way to deal with it? Should I stay with my get/post calls or I should rather use firebase built-in functions? Thank u in advance! :)
Just use Object.values() if you want the array of objects
console.log(Object.values({"-L1cxn3-rLgp7PsPwjV3":{"author":"Mark","title":"Hello"},"-L1cyaOQ4TUYd3m16VfT":{"author":"Lily","title":"Hi"}}))

MongoDB javascript ingest JSON string

I have a big JSON string that is 10 records, each with their own properties. I need to ingest them into my MongoDB with Javascript. I'm basically useless with Javascript, and google has largely failed me. The JSON looks like this, basically:
[{"ID":1,"Name":"bob"},{"ID":2,"Name":"Jim"}]
Obviously a lot more, but that's the basic structure. How would one, using Node.js for example, import that into Mongo? Mongo's documentation largely only covers their shell commands, but those dont' directly translate into Javascript.
You could do a bulk insert like so:
var MyObject = mongoose.model('MyObject', MyObjectSchema);
var objectsArray = [/* array of MyObject objects */];
MyObject.collection.insert(objectsArray, callback);
Well i normally use mongoose plugin driver, to save such a document , define the schema first, at a glance your schema seems to have two fields ID and Name, with id custom. It is custom because mongodb uses it own id, to change this use auto-increment-plugin. So after you define your schema, mongodb will only save or insert a object if the fields match the schema.
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
The above is the format for a document insertion.document document or array A document or array of documents to insert into the collection.
Hope this helps.

Meteor: retrieve value from document in collection

I have a Collection named "balance". I want to get the value of one document in the collection. In order to get only the latest element in the collection I use this query:
db.balance.find().sort({date: -1}).limit(1);
There's a column called 'value' and I want to get that.
db.balance.find().sort({date: -1}).limit(1).value; however does not show the data I want. It shows nothing:
What's wrong with it?
find returns a cursor. You'll need to convert it to an array in order to actually extract the value. Try this:
db.balance.find().sort({date: -1}).limit(1).toArray()[0].value;
This is, of course, much easier inside of meteor (either in code or via meteor shell) because you can do:
Balance.findOne({}, {sort: {date: -1}}).value;

Categories

Resources