Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
Write mongo shell script in TS file

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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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))
over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório

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!

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda