When I'm inserting data to MongoDB it look like this..
_id: "611ddfb55c0ca9fe6df6ae6e"
name:"Residential Real Estate Photography"
price:"989"
without ObjectID,
But I wanted it to be with ObjectId
How to solve this?
The _id field in the MongoDB document is always ObjectID.
If you are talking about getting the value as an object of type ObjectID, you have to convert the string.
For js you can use https://github.com/williamkapke/bson-objectid
To get from string simply do var id = (ObjectID("611ddfb55c0ca9fe6df6ae6e"));
Related
I'm using npgsql to store data about shipments and part of table is jsonb column storing some details about shipment including details about customer who made shipment.
Table for displaying data about shipments is displaying only Customer Name and if get that record via
CustomerName = shipment.Metadata.RootElement.GetProperty("customer").GetProperty("customerName").ToString(),
Request is that I make this column sortable so I would need to sort by this property while accessing database.
Is it even possible to do it in NpgSql?
You can easily sort by a property inside a JSON document - just specify that property in your OrderBy clause:
_ = await ctx.Shipments
.OrderBy(s => s.Metadata.RootElement.GetProperty("customer").GetProperty("customerName").GetString())
.ToListAsync();
This produces the following:
SELECT s."Id", s."Metadata"
FROM "Shipments" AS s
ORDER BY s."Metadata"#>>'{customer,customerName}'
You should probably be able to make this use an index as well.
I am struggling to get pagination working when I use a date (firebase timestamp) to retrieve data.
This is basically what I do:
let jobsRef = db.collection("jobs")
.orderBy('createdAt', 'desc')
.limit(QUERY_LIMIT);
jobsRef = jobsRef.startAfter(this.props.jobs[this.props.jobs.length - 1].createdAt);
However it seems that i get returned items sometimes that I have just already received. I am guessing because of similar dates?
So how could I basically return a list of jobs ordered by createdAt and have an offset/limit (pagination)?
createdAt looks like the timestamp type: 23 October 2020 at 17:26:31 UTC+2
When I log createdAt however I see this: {seconds: 1603537477, nanoseconds: 411000000}
Maybe I should be storing createdAt as a unix timestamp? Or what is the ideal way to deal with this?
Here is how it looks in the database (popup when i click edit on createdAt):
If multiple documents can have the same value for the field you're sorting on, passing in a value for that field is not guaranteed to point to a unique document. So you indeed may be passing in an ambiguous instruction, leading to an unwanted result.
When possible, I highly recommend passing the entire document to the Firestore API. This leaves it up to Firestore to take the necessary data from that document to uniquely/unambiguously find the anchor for your query.
So instead of:
jobsRef.startAfter(this.props.jobs[this.props.jobs.length - 1].createdAt);
Do:
jobsRef.startAfter(this.props.jobs[this.props.jobs.length - 1]);
I was facings a similar problem, after may hours I finally found a solution, all you need to do is converting that number to firestore's Timestamp
import { Timestamp }. from #angular/fire/firestore;
let createdAt: number = 56772766688383;
let timestamp = Timestamp.fromMillis(createdAt);
//then pass that to startAfter
startAfter(timestamp)
I'm manually serializing objects to and from strings and trying to store them in a Postgres database using SqlKata:
var obj = new { Id = 3, JsonB = "{a: 5}" };
dbInstance.Query("TableName").InsertAsync(obj);
The column JsonB is of type jsonb. When I attempt to do it this way, I get the following error:
Exception data:
Severity: ERROR
SqlState: 42804
MessageText: column "DataField" is of type jsonb but expression is of type text
I don't see anywhere in the documentation nor the code to where I can cast types on insert, and am at a loss on how to make it so that I can save JSON strings/objects to the appropriate fields.
I have same problem. For inserts where json column is present in table switched to use NpgsqlCommand and Npgsql.Json.NET library for serializing objects on the fly. Not SqlKata but working:
Product prod;
using (NpgsqlCommand command =
new NpgsqlCommand(#$"INSERT INTO products (json_col) VALUES (#json_col)", connection))
{
command.Parameters.Add(
new NpgsqlParameter("json_col", NpgsqlTypes.NpgsqlDbType.Json) { Value = prod });
await command.ExecuteNonQueryAsync();
}
I don't know SqlKata, but indeed you need to tell Npgsql that you're sending a json (or jsonb) type, since strings are mapped to the PostgreSQL text type by default. PostgreSQL is quite type-strict and will not implicitly cast between most types - you will need to find out how to set NpgsqlDbType via SqlKata.
This is one user's notes. I want to query and get only the notes of this use with "activeFlag:1". My query object code is
findAccountObj =
{ _id: objectID(req.body.accountId),
ownerId: req.body.userId,
bookId: req.body.bookId,
"notes.activeFlag": 1 };
But this query returns all the notes, including the ones with "activeFlag:0".
How do I fix this?
If you are on v2.2, use elementmatch operator. v3.2 and above allow aggregation and filter to return a subset of a document.
here is an example Retrieve only the queried element in an object array in MongoDB collection
I have a MEAN stack application.
In my database, a document has a mongo ObjectId like such :
{ "_id" : ObjectId("57e15b1009cb82cafafafd73"), "name" : "Hello", "artist_id" : "world", "year" : "2000" }
But when I load the document in my front end, the _id gets converted to a string, and my object looks like this when logged in the browser:
{ "_id" : "57e15b1009cb82cafafafd73", "name" : "Hello", "artist_id" : "world", "year" : "2000" }
What is annoying is that when I want to modify my database from my front end (update or delete an existing document), I have to convert the _id from string to ObjectId in order to target the document in my database...
So in my node application, I have to systematically massage the _id with new ObjectId(stringId) because the Id's sent by the browser are strings...
Obvisouly I'm missing out on something.
How can I make things more elegant ?
This is normal to convert string as objectId using ObjectId() because when you are passing it to web it's converted as json string so it is not an objectId anymore but when you are using an objectid from a document at your server side in that case you need not convert it to objectid.
You always need objectId() constructor if your _id type is string.
What module you use for mongodb, I think mongoose?
If you are using mongoose then you do not have to convert your _id into ObjectId, just run the query with string.
db.collection.find({_id: "57e15b1009cb82cafafafd73"});
Thanks for your replies.
So an obvious thing thats going to happen in a MEAN application, is that the ObjectIds of the documents will be converted to strings as they are consumed as JSON objects.
That's going to require heavy use of new ObjectId() when recording objects in the frontend that had their ID generated by Mongo back to the database...
Any other option than using Mongoose ? I'm very happy using the standard node mongo driver for now besides having this string conversion issue...