1

I am trying to set some data in firestore using this node js code :

const db = admin.firestore();
const allDB = db.collection("like").doc("all").collection("movies");
const s1 = db.collection("like").doc("all");
await s1.set({
  type: ["all"],
});

running the file in console : node file.js

Gives me this error :

await s1.set({
^^^^^

SyntaxError: await is only valid in async function
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

How to solve this issue

sabertooth
  • 582
  • 1
  • 7
  • 23
  • In the future, I suggest doing a web search before posting your question. Many times the question has already been asked, and you can be helped by looking at the existing answers. – Doug Stevenson Sep 24 '20 at 18:52

3 Answers3

2

Wrap your code in async function

async function run(){
  const db = admin.firestore();
  const allDB = db.collection("like").doc("all").collection("movies");
  const s1 = db.collection("like").doc("all");
  await s1.set({
    type: ["all"],
  });
}

run().catch(e => { console.error(e); process.exit(-1); })
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
2

You should use it inside an async function, this will work:

const doSomething = async () => {
  const db = admin.firestore();
  const allDB = db.collection("like").doc("all").collection("movies");
  const s1 = db.collection("like").doc("all");
  await s1.set({
    type: ["all"],
  });
}
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
0

like in the answer above, you just need to make an async function by using the async title thing, then naming a function with the stuff inside it

Josh
  • 119
  • 1
  • 11