如何将新的数组索引推送到数据库 属性,同时保持已存储的数据不受影响?
How do I push a new array index into a database property, keeping the data already stored untouched?
我有一些代码可以上传图像并更新名为 'images' 的图像 URL 数组 属性,其中每个图像 url 都存储在数组。
我在下面尝试使用 db.doc(`/posts/${req.params.postId}`).update({ images: images.push(image) });
的功能
但是我遇到了一个错误。有没有人有一个简单的方法来做到这一点?非常感谢任何帮助!
exports.uploadImage = (req, res) => {
// res.send("this worked"); // everything works up to this point
const Busboy = require("busboy");
const path = require("path");
const os = require("os");
const fs = require("fs");
const busboy = new Busboy({ headers: req.headers });
let imageToBeUploaded = {};
let imageFileName;
// res.send("this worked");
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
console.log(fieldname, file, filename, encoding, mimetype);
if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
return res.status(400).json({ error: "Wrong file type submitted" });
}
// my.image.png => ['my', 'image', 'png']
const imageExtension = filename.split(".")[filename.split(".").length - 1];
// 32756238461724837.png
imageFileName = `${Math.round(
Math.random() * 1000000000000
).toString()}.${imageExtension}`;
const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
admin
.storage()
.bucket()
.upload(imageToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype
}
}
})
.then(() => {
const image = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
return db.doc(`/posts/${req.params.postId}`).update({ images: **images.push(image)** });
})
.then(() => {
return res.json({ message: "image uploaded successfully" });
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: "something went wrong" });
});
});
busboy.end(req.rawBody);
};
如果要在 images
字段中保留一组唯一值,可以使用 array-union
操作。来自 documentation on updating an array:
let admin = require('firebase-admin');
// ...
let washingtonRef = db.collection('cities').doc('DC');
// Atomically add a new region to the "regions" array field.
let arrUnion = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
// Atomically remove a region from the "regions" array field.
let arrRm = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayRemove('east_coast')
});
如果您对同一文档多次调用 washingtonRef.update({ regions: admin.firestore.FieldValue.arrayUnion('greater_virginia') })
,该文档中的 regions
数组仍将只包含一次 greater_virginia
。
这是在不知道数组中现有项的情况下向数组添加值的唯一方法。更新数组的唯一方法是首先读取该数组,然后在代码中将您的值添加到它,最后将结果写回 Firestore。
我有一些代码可以上传图像并更新名为 'images' 的图像 URL 数组 属性,其中每个图像 url 都存储在数组。
我在下面尝试使用 db.doc(`/posts/${req.params.postId}`).update({ images: images.push(image) });
但是我遇到了一个错误。有没有人有一个简单的方法来做到这一点?非常感谢任何帮助!
exports.uploadImage = (req, res) => {
// res.send("this worked"); // everything works up to this point
const Busboy = require("busboy");
const path = require("path");
const os = require("os");
const fs = require("fs");
const busboy = new Busboy({ headers: req.headers });
let imageToBeUploaded = {};
let imageFileName;
// res.send("this worked");
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
console.log(fieldname, file, filename, encoding, mimetype);
if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
return res.status(400).json({ error: "Wrong file type submitted" });
}
// my.image.png => ['my', 'image', 'png']
const imageExtension = filename.split(".")[filename.split(".").length - 1];
// 32756238461724837.png
imageFileName = `${Math.round(
Math.random() * 1000000000000
).toString()}.${imageExtension}`;
const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
admin
.storage()
.bucket()
.upload(imageToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype
}
}
})
.then(() => {
const image = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
return db.doc(`/posts/${req.params.postId}`).update({ images: **images.push(image)** });
})
.then(() => {
return res.json({ message: "image uploaded successfully" });
})
.catch(err => {
console.error(err);
return res.status(500).json({ error: "something went wrong" });
});
});
busboy.end(req.rawBody);
};
如果要在 images
字段中保留一组唯一值,可以使用 array-union
操作。来自 documentation on updating an array:
let admin = require('firebase-admin'); // ... let washingtonRef = db.collection('cities').doc('DC'); // Atomically add a new region to the "regions" array field. let arrUnion = washingtonRef.update({ regions: admin.firestore.FieldValue.arrayUnion('greater_virginia') }); // Atomically remove a region from the "regions" array field. let arrRm = washingtonRef.update({ regions: admin.firestore.FieldValue.arrayRemove('east_coast') });
如果您对同一文档多次调用 washingtonRef.update({ regions: admin.firestore.FieldValue.arrayUnion('greater_virginia') })
,该文档中的 regions
数组仍将只包含一次 greater_virginia
。
这是在不知道数组中现有项的情况下向数组添加值的唯一方法。更新数组的唯一方法是首先读取该数组,然后在代码中将您的值添加到它,最后将结果写回 Firestore。