You can use mongoose, this example is for a 'Product' Schema, you can read about mongoose Schemas here: https://mongoosejs.com/docs/guide.html
require mongoose, require your product model (schema), connect to your DB (this example called 'myDB'), and then call getProduct() function.
getProduct() will find a document with id: '5f323812akqwie123kasdid', set your data to update as you want, then call the updateProduct() function.
This function calls findByIdAndUpdate() and accept as arguments the product id to update, and the product updated.
const mongoose = require('mongoose');
const Product = require('./models/product.model');
const settings = { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false };
mongoose.connect("mongodb://localhost:27017/myDB", settings, (err) => {
if (!err) { console.log('MongoDB connection succeeded.'); }
else { console.log('Error in MongoDB connection : ' + JSON.stringify(err, undefined, 2)); }
getProduct();
});
const getProduct = async () => {
try {
let product = await Product.findById("5f323812akqwie123kasdid"); // find
let dataToUpdate = {new: 'data'}; // your data to insert
let lastItem = product.arrayA.pop() // remove last item of array and stores in a new variable
lastItem.arrayB = [dataToUpdate]; // set your data to arrayB property
product.arrayA.push(lastItem); // push the updated item
updateProduct(product._id, product);
}
catch(e) {
console.log(e)
}
}
const updateProduct = async (productId, update) => {
let productUpdated = await Product.findByIdAndUpdate(productId, update, {new: true});
console.log(productUpdated);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…