Firebase批处理集包含无效数据

y1aodyip  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(110)

错误消息:使用无效数据调用了函数WriteBatch.set()。数据必须是对象,但它是:www.google.com
我有一个按钮,onclick运行addQuotes函数。
我哪里做错了?

const addQuotes = async () => {
      let test = ['https://www.google.com/', 'https://www.google.com/about',]
      const obj1 = Object.assign({}, test);
      const batch = writeBatch(db);

Object.keys(obj1).forEach(key => {
  var docRef = db.collection("col").doc(); //automatically generate unique id
  batch.set(docRef, obj1[key]);
});

 batch.commit().then(function () {
        console.log("hello")
    });
}
yqyhoc1h

yqyhoc1h1#

正如错误所述,data参数应该是一个对象(batch.set方法的第二个参数)

  • 注解了用于运行代码的firebase方法调用,并向您展示了o/p
// In your case when you do 
let test = ['https://www.google.com/', 'https://www.google.com/about', ]
const obj1 = Object.assign({}, test);

console.log(obj1);

// and ignoring the unique id step

Object.keys(obj1).forEach((key, index) => {
  // var docRef = db.collection("col").doc(); //automatically generate unique id
  
  console.log(obj1[key]);  // here it is just the string value
  
  console.log({[index]: obj1[key]}); // here it is an object
  
  //when you do the bellow line
  // batch.set(docRef, obj1[key]); // value of obj1[key] is just string which is not the correct type 
  
  // may be you do something as below (key can be as you want it to be)
  // batch.set(docRef, {[index]: obj1[key]});  // index is added as key for the object which in now an object and should work
  
});

我使用了{[index] : obj1[key]}表示法,即computed property in object
希望是清楚的🙂

相关问题