简体   繁体   English

在 MongoDB 文档中,使用 Node JS,如何找到数组中的最后一项,并将文档插入到该项的子数组中?

[英]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 MongoDB文件结构

 { 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?使用 MongoDB Node JS,我想在 arrayA 中找到最后一个 object,并将 object 插入到所述对象的 arrayB 中,我应该如何编写搜索查询?

You can use mongoose, this example is for a 'Product' Schema, you can read about mongoose Schemas here: https://mongoosejs.com/docs/guide.html您可以使用 mongoose,此示例适用于“产品”架构,您可以在此处阅读有关 mongoose 架构的信息: 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.需要 mongoose,需要您的产品 model(架构),连接到您的数据库(此示例称为“myDB”),然后调用 getProduct() function。

getProduct() will find a document with id: '5f323812akqwie123kasdid', set your data to update as you want, then call the updateProduct() function. getProduct() 将找到 ID 为“5f323812akqwie123kasdid”的文档,将数据设置为根据需要更新,然后调用 updateProduct() function。

This function calls findByIdAndUpdate() and accept as arguments the product id to update, and the product updated.此 function 调用 findByIdAndUpdate() 并接受要更新的产品 ID 作为 arguments,并且产品已更新。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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