函数只将一个元素添加到收藏夹数组中



我刚刚意识到我的markFavorite函数只会将一个元素添加到收藏夹数组中,一旦我尝试添加另一个元素,它就会记录:

"FirebaseError:使用无效数据调用了函数updateDoc((。不支持的字段值:未定义(在文档中找到users/l2c8ieJurAfrqI1Pj6wNWro1S2u2(";

我可以继续添加一个元素而不会出现问题,但一旦我尝试添加另一个元素,就会出现此错误。

这是功能代码:

async function markFavorite(did, nombre, comentarios, valor) {
try {
const docRef = doc(db, "users", auth.currentUser.uid);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document.data:", docSnap.data());
const favoriteUpdate = {
favorite: true,
id: did,
nombre: nombre,
comentarios: comentarios,
valor: valor,
};
let favoritesUpdate;
const favorites = docSnap.data().favorites;
// Checking if the array is empty or not. If it is empty, it will add the new item to the array.
// If it is not empty, it will check if the item is already in the array. If it is, it will update
// the item. If it is not, it will add the new item to the array.
if (favorites && favorites.length) {
const findAuto = favorites.find((item) => item.id === did);
if (findAuto) {
favoritesUpdate = favorites.map((item) =>
item.id === did ? favoriteUpdate : item
);
} else {
// Adding the new item to the array.
favoritesUpdate = [...favorites, favoritesUpdate];
}
} else {
// Adding the new item to the array.
favoritesUpdate = [favoriteUpdate];
}
// Updating the document with the new array.
await updateDoc(docRef, {
favorites: favoritesUpdate,
});
alert("¡Añadido a tus favoritos!");
} else {
console.log("No se localiza este documento!");
}
} catch (error) {
console.log(error);
}
}

如果有人能就问题所在提出建议,我将不胜感激

很可能您的函数没有得到它所期望的所有参数。

你有几个解决方案:

  • 如果函数参数都是必需的,则包装函数内容在:

    if(!did && !nombre && !comentarios && !valor){
    // Your function code here   } else {
    console.log('Missing markFavorite function arguments', {...arguments};
    // Could also throw error: throw new Error['Missing arguments']   } } ```
    
  • 否则,如果您同意这些值为空,则可以设置自变量为空时的默认值:

    async function markFavorite(did = '', nombre = null, comentarios = {}, valor = '') { 
    // Your function code here 
    } 
    

    显然,设置默认值以匹配您的数据模型/模式。

  • 您也可以告诉Firestore忽略未定义的值,例如不将undefined的属性写入Firestore,但这可能是最后的选择,因为这样您的数据模型/架构将不一致。

    以下是适用于Firestore 的数据类型

    你必须像这样初始化消防仓库,使用ignoreUndefinedProperties选项:

    import { initializeFirestore } from "firebase/firestore"
    const db = initializeFirestore( app, { ignoreUndefinedProperties: true })
    

我成功地复制了您的错误消息。我们得到这种错误是因为favoritesUpdate声明不包含任何值,这就是为什么favoritesUpdate = [...favorites, favoritesUpdate]被返回为未定义的原因。解决此问题的一种方法是,可以使用Firestore提供的方法arrayUnion(),因为它向数组中添加元素,但只添加尚未存在的元素。您的第一个else语句应该是这样的:

else {
// Adding the new item to the array.
favoritesUpdate = arrayUnion(favoriteUpdate);
}

您可以查看有关更新数组中元素的文档。

这里有一个示例工作代码供您参考:

async function markFavorite(did, nombre, comentarios, valor) {
try {
const docRef = doc(db, "users", auth.currentUser.uid);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document.data:", docSnap.data());
const favoriteUpdate = {
favorite: true,
id: did,
nombre: nombre,
comentarios: comentarios,
valor: valor,
};
let favoritesUpdate;
const favorites = docSnap.data().favorites;
// Checking if the array is empty or not. If it is empty, it will add the new item to the array.
// If it is not empty, it will check if the item is already in the array. If it is, it will update
// the item. If it is not, it will add the new item to the array.
if (favorites && favorites.length) {
const findAuto = favorites.find((item) => item.id === did);
if (findAuto) {
favoritesUpdate = favorites.map((item) =>
item.id === did ? favoriteUpdate : item
);
} else {
// Adding the new item to the array.
favoritesUpdate = arrayUnion(favoriteUpdate); //--> This is the one I changed
}
} else {
// You can also use arrayUnion here if there's no data on the document. This will produce the same result.
// favoritesUpdate = arrayUnion(favoriteUpdate);
// Adding the new item to the array.
favoritesUpdate = [favoriteUpdate];
}

// Updating the document with the new array.
await updateDoc(docRef, {
favorites: favoritesUpdate,
});
console.log("¡Añadido a tus favoritos!");
} else {
console.log("No se localiza este documento!");
}
} catch (error) {
console.log(error);
}
}

问题是由于打字错误引起的:

else {
// Adding the new item to the array.
favoritesUpdate = [...favorites, favoritesUpdate];
}

它实际上必须是:

else {
// Adding the new item to the array.
favoritesUpdate = [...favorites, favoriteUpdate];
}

最新更新