Node.js 如何将新的数组索引推入数据库属性中,使已存储的数据保持不变?
我有一些代码可以上传一个图像以及更新一个名为“images”的图像URL数组属性,其中每个图像URL都存储在数组的索引中 我在下面的函数中尝试使用Node.js 如何将新的数组索引推入数据库属性中,使已存储的数据保持不变?,node.js,firebase,google-cloud-firestore,busboy,Node.js,Firebase,Google Cloud Firestore,Busboy,我有一些代码可以上传一个图像以及更新一个名为“images”的图像URL数组属性,其中每个图像URL都存储在数组的索引中 我在下面的函数中尝试使用db.doc(`/posts/${req.params.postId}').update({images:images.push(image)}) 但我遇到了一个错误。有没有人有一个简单的方法来做到这一点?我真的很感激任何帮助 exports.uploadImage = (req, res) => { // res.send("this w
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
操作。从:
如果要对同一文档多次调用washingtonRef.update({regions:admin.firestore.FieldValue.arrayUnion('greater_virginia')})
,则该文档中的regions
数组仍将只包含greater_virginia
一次
这是在不知道数组中现有项的情况下向数组添加值的唯一方法。更新数组的唯一方法是首先读取该数组,然后在代码中为其添加值,最后将结果写回Firestore。这似乎完成了我所需要的。感谢您向我展示该文档并对其进行解释!
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')
});