简体   繁体   中英

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"] } ] }

Using MongoDB Node JS, I want to find the last object in arrayA, and insert an object into said object's arrayB, how should I write the search query?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM