Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - In a MongoDB document, using Node JS, how do I find the last item in an array, and insert a document into said item's sub-array?

MongoDB document structure

{
  data:"data"
  arrayA:
  [
    {
      newData:"0",
      arrayB:["something","something"]
    },
    {
      newData:"1",
      arrayB:["something"]
    }
    
  ]
  
}
question from:https://stackoverflow.com/questions/65939490/in-a-mongodb-document-using-node-js-how-do-i-find-the-last-item-in-an-array-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...