I am trying to create a function which can perform an insert and return the response object from MongoDB, so I can take the _id of the document and use it in another function.
What I am trying to do is multiple awaits.
let {insertId: userId } = await newUser(...)
let {insertId: telId} = await assignTelelephone({userId: userId, .... })
let {... } = await updateUser({_id: userId, ... } )
But although the function does work, the return is undefined
. I expect the function to return an Ok(dataObject) or an Error(errorMessage). What am I missing?
}
module ClientInstance = {
type t
@send external db: (t, string) => Db.t = "db"
}
module Client = {
type t
@module("mongodb") @new external make: string => t = "MongoClient"
@send external connect: t => Promise.t<ClientInstance.t> = "connect"
@send external close: t => unit = "close"
}
let uri = "mongodb://localhost:27017"
let dbName = "rescript"
// The user I want to insert
type user = {firstName: string, lastName: string, isLearningRescript: bool}
let alex = {firstName: "Alex", lastName: "Kleydints", isLearningRescript: true}
/* The function to insert one user. Takes in a user and returns an object of
type insertResponse
*/
let insertOne = (user: user) => {
open Promise
let client = Client.make(uri)
client
->Client.connect
->then(instance => {
instance->ClientInstance.db(dbName)->Db.collection("users")->resolve
})
->then(collection => {
collection->Collection.insertOne(user)->resolve
})
->thenResolve(result => {
Js.log2("thenResolve", result)
result->Ok
})
->catch(e => {
let errorMsg = switch e {
| JsError(obj) =>
switch Js.Exn.message(obj) {
| Some(msg) => msg
| None => "Unknown Js Error"
}
| _ => "Unknown non-JS error"
}
Js.log(errorMsg)
errorMsg->Error->resolve
})
->finally(() => {
client->Client.close
})
->ignore
}
let result = insertOne(alex)
Js.log2("result", result)
It compiles and when I run it it gives:
~/rescript/rescript-play/src$ node Mongo.bs.js
result undefined
thenResolve {
acknowledged: true,
insertedId: new ObjectId("61027bfff749b20c30076abf")
}
Thank you in advance.