【问题标题】: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 文档中,使用 Node JS,我如何找到数组中的最后一项,并将文档插入到所述项的子数组中?
【发布时间】:2021-01-28 14:49:02
【问题描述】:

MongoDB 文档结构

{
  data:"data"
  arrayA:
  [
    {
      newData:"0",
      arrayB:["something","something"]
    },
    {
      newData:"1",
      arrayB:["something"]
    }
    
  ]
  
}

使用MongoDB Node JS,我想在arrayA中找到最后一个对象,并将一个对象插入到该对象的arrayB中,我应该如何编写搜索查询?

【问题讨论】:

  • 你有这个数据结构的架构吗?
  • 我问题中的代码 sn-p 是我要对其执行操作的数据结构。
  • 在节点中你可以使用 mongoose 来处理 mongoDB,要与 DB 交互你必须定义一个数据模式

标签: javascript node.js arrays mongodb


【解决方案1】:

您可以使用 mongoose,此示例用于“产品”架构,您可以在此处阅读有关 mongoose 架构的信息:https://mongoosejs.com/docs/guide.html

需要 mongoose,需要您的产品模型(模式),连接到您的数据库(此示例称为“myDB”),然后调用 getProduct() 函数。

getProduct() 会找到一个 id: '5f323812akqwie123kasdid' 的文档,根据需要设置数据更新,然后调用 updateProduct() 函数。

此函数调用 findByIdAndUpdate() 并接受要更新的产品 ID 和更新的产品作为参数。

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

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2014-07-29
    • 2014-08-02
    • 2012-05-19
    • 1970-01-01
    • 2015-06-09
    • 2017-09-14
    • 1970-01-01
    • 2015-12-19
    相关资源
    最近更新 更多