_alex
(Alex)
September 28, 2021, 1:47pm
#1
Normally, when using findOne()
command, one will get an object that will look like this:
{
id: "...",
createdAt: "..."
}
I would like this object to be in the same form I can see when inserting documents in Atlas, or using mongoexport
:
{
id: {
$oid: "..."
},
createdAt: {
$date: "..."
}
}
Is that possible with the findOne()
method, or some other approach?
I am trying to do it in a Realm function, so using database tools, like mongoexport
, are not an option.
MaBeuLux88
(Maxime Beugnet)
September 28, 2021, 7:09pm
#2
Hi @_alex ,
Would that work for you?
exports = function(arg){
const coll = context.services.get("mongodb-atlas").db("test").collection("test");
return coll.findOne().then((doc) => {
const s = EJSON.stringify(doc);
console.log(s);
return s;
});
};
Result:
> ran on Tue Sep 28 2021 21:07:39 GMT+0200 (Central European Summer Time)
> took undefined
> logs:
{"_id":{"$oid":"61536690650d531e1c196bdd"},"date":{"$date":{"$numberLong":"1293922800000"}}}
> result:
"{\"_id\":{\"$oid\":\"61536690650d531e1c196bdd\"},\"date\":{\"$date\":{\"$numberLong\":\"1293922800000\"}}}"
> result (JavaScript):
EJSON.parse('"{\"_id\":{\"$oid\":\"61536690650d531e1c196bdd\"},\"date\":{\"$date\":{\"$numberLong\":\"1293922800000\"}}}"')
If I use the JSON
helper instead of the EJSON
one, I get this result instead:
> ran on Tue Sep 28 2021 21:08:42 GMT+0200 (Central European Summer Time)
> took undefined
> logs:
{"_id":"61536690650d531e1c196bdd","date":"2011-01-01T23:00:00.000Z"}
> result:
"{\"_id\":\"61536690650d531e1c196bdd\",\"date\":\"2011-01-01T23:00:00.000Z\"}"
> result (JavaScript):
EJSON.parse('"{\"_id\":\"61536690650d531e1c196bdd\",\"date\":\"2011-01-01T23:00:00.000Z\"}"')
Doc for the different helpers available: https://docs.mongodb.com/realm/functions/json-and-bson/
Cheers,
Maxime.
1 Like
_alex
(Alex)
September 29, 2021, 11:01am
#3
Thank you so much, @MaBeuLux88 . This is exactly what I was looking for!
1 Like
system
(system)
Closed
October 4, 2021, 11:02am
#4
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.