2

I have a mongo-init.js which creates some testing data when the app boots up:

// Create admin user for reading and writing data from server
db.createUser({
  user: "admin",
  pwd: "password",
  roles: [
    {
      role: "readWrite",
      db: "authStarterDB",
    },
  ],
});

// Create testing data
// User - email: test@gmail.com, username: test, psw: qweqweqwe
let res = [
  db.users.drop(),
  db.users.createIndex({ email: 1 }, { unique: true }),
  db.users.createIndex({ username: 1 }, { unique: true }),
  db.users.insert({
    email: "test@gmail.com",
    username: "test",
    salt: "62a633a7a64abd1909c69aa78259cff1258dd335c8c7a453de09e6801cd46b36",
    hash:
      "fc3042f428d75d266d8cf799536a2d7ed743d0cdab5bb086ad9379caa3f6d136bdcef3e746c4591272886e62e64fd2e6205c3479d257d06bc28f476919e6c6c0d7ee3a91f74eda3b851862baa51c45a666f295993e96e3c98c614af59a80d0857d735d7dd31070e36901309efe25fb81b363684d830545cb75d4787f045da82d10f308332fc0d7bf1b85c0ae5c601025e64f437947dc92ac319c294fb92e38106261ba47d004105afab6ad5a2af3d582a8897dc180ff97cedb775bc90082207387de92a18da293f4831e6efd89277fe128df9d0889c8e16b3e56c7b00bb66805108e7a7996d43b2754c8dcf8540347a67ffee4f8a866311afcfb59efa9c4c35fcd3f089e69fb04e77a2b11a49d904271b890e0e785902ebf11d620cbc7845f1762bc71df7163220e293b122cd6a35ce9d1359057cedb3da8c55bd29fab0261e2886bbf9d7f11d5782a5377be0c5e01b8bf3fe69cb0895d23f5604d08e5d4d09669f4448a1d102696ac053e77d0d413922cda7e4e51d71e606441ffea1bcb1dbe7d777a48548ec2df42a3c8d076f599919cd359fe622ba9a2193d38bb1e13dc2db1827c0ba20e52be3210778bb4fec8a7ae0b7f385a23aeac2592091f645146dc4ebea20efba6ed921871b1dae8841b07670762aa0312156fe02bb7b68ec06b34a7bca1ee4d2276483915eb753580afc20467abccbea9c506c118f290756c5fe7",
    createdAt: ISODate("2020-01-01T00:00:00.174Z"),
    updatedAt: ISODate("2020-01-01T00:00:00.174Z"),
  }),
];
printjson(res);

I've converted the whole app to use Typescript, but I'm unsure how to go with this file, since it is not really javascript.

From the compiler I get Cannot find name ''.ts(2304) for 'db', 'ISODate' and 'printjson'.

I thought this could perhaps be converted to a .sh script instead, but having a look around I encountered this q/a suggesting to write mongodb scripts directly on a js file.

So is there a way to declare types for mongodb commands? Or how could this be tackled if otherwise?

ale917k
  • 1,494
  • 7
  • 18
  • 37
  • converting js to typescript is essentially adding type definitions to everything and will result in a js file after compilation anyway, those errors suggest you are not using the mongodb types npm package: @types/mongodb, as well as not working in scope. to remove type errors (disable the compiler type checks) you can declare a variable to be of type `any` - but that kind of makes you wonder why use typescript in this case in the first place – BigFatBaby Apr 12 '21 at 15:25

3 Answers3

3

You should use mongodb driver to execute mongo scripts. Also since you're using typescript you should also install mongo types. Read the docs about mongodb nodejs driver. It's really easy to use.
Also functions like printjosn or ISODate do not exist in javascript.

  1. Instead ISODate("2020-01-01T00:00:00.174Z") you should use new Date("2020-01-01T00:00:00.174Z")
  2. Instead of printjson(res) use ether console.log(res) or console.log(JSON.stringify(res, null, 2))
Serhiy Mamedov
  • 1,080
  • 5
  • 11
2

You can't use Typescript in this file, because you run it with mongo shell, which doesn't support Typescript.

If you'd like to use Typescript in this file, you'll have to compile it with tsc and then run the resulting JS file in mongo shell.

This will be tricky, because I couldn't find any ready-made type definitions for things such as db.createUser and printjson, which means that you'll have to define these types by yourself, not ideal IMO.

As suggested by Serhiy Mamedov, you can instead use mongodb package from npm with appropriate types from DT in order to create new user, drop collection, etc.

Essentially, I suggest you rewrite the script from mongo shell environment to NodeJS environment, where you'll have ready-made quality type definitions.

As you can see in this question OP was trying to use createUser() function from mongo shell environment inside NodeJS environment, and failed. Because in NodeJS environment the same function is called addUser().

Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
0

if you are looking to execute above commands in mongo shell then you may have javascript file with below contents:

var createUserResult = db.createUser({
    user: "admin",
    pwd: "password",
    roles: [
        {
            role: "readWrite",
            db: "authStarterDB",
        },
    ],
});
print("createUserResult:", JSON.stringify(createUserResult));

// Create testing data
// User - email: test@gmail.com, username: test, psw: qweqweqwe
//
var dropUserResult = db.users.drop();
print('dropUserResult:', JSON.stringify(dropUserResult));

var emailIndexResult = db.users.createIndex({ email: 1 }, { unique: true });
print('emailIndexResult:', JSON.stringify(emailIndexResult));
var usernameIndexResult = db.users.createIndex({ username: 1 }, { unique: true });
print('usernameIndexResult:', JSON.stringify(usernameIndexResult));
var userInsertResult = db.users.insert({
    email: "test@gmail.com",
    username: "test",
    salt: "62a633a7a64abd1909c69aa78259cff1258dd335c8c7a453de09e6801cd46b36",
    hash:
        "fc3042f428d75d266d8cf799536a2d7ed743d0cdab5bb086ad9379caa3f6d136bdcef3e746c4591272886e62e64fd2e6205c3479d257d06bc28f476919e6c6c0d7ee3a91f74eda3b851862baa51c45a666f295993e96e3c98c614af59a80d0857d735d7dd31070e36901309efe25fb81b363684d830545cb75d4787f045da82d10f308332fc0d7bf1b85c0ae5c601025e64f437947dc92ac319c294fb92e38106261ba47d004105afab6ad5a2af3d582a8897dc180ff97cedb775bc90082207387de92a18da293f4831e6efd89277fe128df9d0889c8e16b3e56c7b00bb66805108e7a7996d43b2754c8dcf8540347a67ffee4f8a866311afcfb59efa9c4c35fcd3f089e69fb04e77a2b11a49d904271b890e0e785902ebf11d620cbc7845f1762bc71df7163220e293b122cd6a35ce9d1359057cedb3da8c55bd29fab0261e2886bbf9d7f11d5782a5377be0c5e01b8bf3fe69cb0895d23f5604d08e5d4d09669f4448a1d102696ac053e77d0d413922cda7e4e51d71e606441ffea1bcb1dbe7d777a48548ec2df42a3c8d076f599919cd359fe622ba9a2193d38bb1e13dc2db1827c0ba20e52be3210778bb4fec8a7ae0b7f385a23aeac2592091f645146dc4ebea20efba6ed921871b1dae8841b07670762aa0312156fe02bb7b68ec06b34a7bca1ee4d2276483915eb753580afc20467abccbea9c506c118f290756c5fe7",
    createdAt: ISODate("2020-01-01T00:00:00.174Z"),
    updatedAt: ISODate("2020-01-01T00:00:00.174Z"),
});

print("userInsertResult:", JSON.stringify(userInsertResult));

Then you may use load command to execute the script like load('script.js')

hope this helps, if still looking for something else then pls let me know will try to see if I could help!

  • The code I wrote in the question works perfectly fine, there is no need for refactoring - As posed, I am just looking for a way to convert the above file to typescript – ale917k Apr 10 '21 at 07:10
  • okay so do you think https://medium.com/swlh/using-typescript-with-mongodb-393caf7adfef this blog might help you? – Programmer Analyst Apr 10 '21 at 19:33
  • It does not, please read carefully the question to understand what I'm looking for – ale917k Apr 11 '21 at 08:26