草庐IT

node.js - 基于名称的 MongoDB/Mongoose 连接

coder 2023-10-30 原文

我目前有一个产品架构,其中包含一个包含不同数量对象的属性数组。一个对象看起来像这样:

[{ property: 'Color', value: 'Black' }, { property: 'Length', value: '1 inch' }]

每个产品都有随机数量的属性。问题是我无法查找产品并使用其标识符获取其属性。

下面是产品架构。

const mongoose = require('mongoose');

let product = new mongoose.Schema({
    id: { type: mongoose.Schema.Types.ObjectId },
    created_at: { type: Date, default: new Date()},
    language: { type: String, required: true },
    category: { type: String },
    articlenumber: { type: String },
    name: { type: String },
    properties: { type: [{}] }
});

module.exports = product;

我的属性集合中还有一个带有标识符的属性模式。

const mongoose = require('mongoose');

let property = new mongoose.Schema({
    id: { type: mongoose.Schema.Types.ObjectId },
    categoryPropertyId: { type: String },
    language: { type: String },
    name: { type: String, unique: true }
});

module.exports = property;

{ id: ObjectID, categoryPropertyId: '317', language: 'US', name: 'Color' }

我想获取一个产品并根据其名称和语言加入并获取 categoryPropertyId。

Mongoose 可以吗?我可以使用 javascript 循环来完成,但更喜欢加入之类的东西。

我查看了 $lookup 和 populate,但我对 mongoose 不是很熟练。感谢您的帮助!

一个产品

{
    _id: 5b3f18d93098293c4ab0ca4a,
    created_at: ‘2018-07-06 09:22:45.377’,
    language: ‘US’,
    category: ‘Phones’,
    articlenumber: ‘6700’,
    name: ‘Sony Phone’
    properties: [
    {
        property: ‘Version’,
        helptext: ‘’,
        value: ’8.0’    
    },
    {
        property: ‘Operating System’,
        helptext: ‘’,
        value: ‘Android’
    }]
}

属性数据集

[
    {
        id: ‘5b3603a56a14e1072ba6f4ef’,
        categoryPropertyId: ’429’,
        language: ‘US’,
        name: ‘Android’
    },
    {
        id: ‘5b3603a56a14e1072ba6f4ef’,
        categoryPropertyId: ’977’,
        language: ‘US’,
        name: ‘Version’
    },
    {
        id: ‘5b3603a56a14e1072ba6f4ef’,
        categoryPropertyId: ’1033’,
        language: ‘US’,
        name: ‘Weight’
    }
]

预期输出

{
    _id: 5b3f18d93098293c4ab0ca4a,
    created_at: ‘2018-07-06 09:22:45.377’,
    language: ‘US’,
    category: ‘Phones’,
    articlenumber: ‘6700’,
    name: ‘Sony Phone’
    properties: [
        {
            property: ‘Version’,
            helptext: ‘’,
            value: ’8.0’,
            categoryPropertyId: ’977’
        },
        {
            property: ‘Operating System’,
            helptext: ‘’,
            value: ‘Android’,
            categoryPropertyId: ’429’
        }
    ]
}

最佳答案

您可以尝试以下聚合

基本上你需要先$unwind "properties" 数组与外国“名称”相匹配... let让你 将字段从根文档(产品)保留到内部文档(属性),最后使用 $group 您可以将拆分后的“属性”再次回滚到“属性”数组。

如果你有 mongodb 版本 3.6

db.product.aggregate([
  { "$unwind": "$properties" },
  { "$lookup": {
    "from": Properties.collection.name,
    "let": { "property": "$properties.property" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$name", "$$property" ] } } },
      { "$project": { "categoryPropertyId": 1 }}
    ],
    "as": "properties.prop"
  }},
  { "$unwind": "$properties.prop" },
  { "$addFields": { 
    "properties.categoryPropertyId": "$properties.prop.categoryPropertyId" 
  }},
  { "$project": { "properties.prop": 0 }},
  { "$group": {
    "_id": "$_id",
    "created_at": { "$first": "$created_at" },
    "language": { "$first": "$language" },
    "category": { "$first": "$category" },
    "articlenumber": { "$first": "$articlenumber" },
    "name": { "$first": "$name" },
    "properties": { "$push": "$properties" }
  }}
])

如果你的 mongodb 版本低于 3.6

db.product.aggregate([
  { "$unwind": "$properties" },
  { "$lookup": {
    "from": Properties.collection.name,
    "localField": "properties.property",
    "foreignField": "name",
    "as": "properties.prop"
  }},
  { "$unwind": "$properties.prop" },
  { "$addFields": { 
    "properties.categoryPropertyId": "$properties.prop.categoryPropertyId" 
  }},
  { "$project": { "properties.prop": 0 }},
  { "$group": {
    "_id": "$_id",
    "created_at": { "$first": "$created_at" },
    "language": { "$first": "$language" },
    "category": { "$first": "$category" },
    "articlenumber": { "$first": "$articlenumber" },
    "name": { "$first": "$name" },
    "properties": { "$push": "$properties" }
  }}
])

关于node.js - 基于名称的 MongoDB/Mongoose 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51538456/

有关node.js - 基于名称的 MongoDB/Mongoose 连接的更多相关文章

  1. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  2. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  3. 叮咚买菜基于 Apache Doris 统一 OLAP 引擎的应用实践 - 2

    导读:随着叮咚买菜业务的发展,不同的业务场景对数据分析提出了不同的需求,他们希望引入一款实时OLAP数据库,构建一个灵活的多维实时查询和分析的平台,统一数据的接入和查询方案,解决各业务线对数据高效实时查询和精细化运营的需求。经过调研选型,最终引入ApacheDoris作为最终的OLAP分析引擎,Doris作为核心的OLAP引擎支持复杂地分析操作、提供多维的数据视图,在叮咚买菜数十个业务场景中广泛应用。作者|叮咚买菜资深数据工程师韩青叮咚买菜创立于2017年5月,是一家专注美好食物的创业公司。叮咚买菜专注吃的事业,为满足更多人“想吃什么”而努力,通过美好食材的供应、美好滋味的开发以及美食品牌的孵

  4. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  5. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  6. kvm虚拟机安装centos7基于ubuntu20.04系统 - 2

    需求:要创建虚拟机,就需要给他提供一个虚拟的磁盘,我们就在/opt目录下创建一个10G大小的raw格式的虚拟磁盘CentOS-7-x86_64.raw命令格式:qemu-imgcreate-f磁盘格式磁盘名称磁盘大小qemu-imgcreate-f磁盘格式-o?1.创建磁盘qemu-imgcreate-fraw/opt/CentOS-7-x86_64.raw10G执行效果#ls/opt/CentOS-7-x86_64.raw2.安装虚拟机使用virt-install命令,基于我们提供的系统镜像和虚拟磁盘来创建一个虚拟机,另外在创建虚拟机之前,提前打开vnc客户端,在创建虚拟机的时候,通过vnc

  7. ruby-on-rails - 应用程序的名称是否可以作为变量使用? - 2

    当我创建一个Rails应用程序时,控制台:railsnewfoo我的代码可以使用字符串“foo”吗?puts"Yourapp'snameis"+app_name_bar 最佳答案 Rails.application.class将为您提供应用程序的全名(例如YourAppName::Application)。从那里您可以使用Rails.application.class.parent获取模块名称。 关于ruby-on-rails-应用程序的名称是否可以作为变量使用?,我们在StackOve

  8. ruby-on-rails - 如何从过时的 TZInfo 标识符中获取 Rails TimeZone 名称? - 2

    已经有一个问题回答了如何将“America/Los_Angeles”转换为“PacificTime(US&Canada)”。但是我想将“美国/太平洋”和其他过时的时区转换为RailsTimeZone。我无法在图书馆中找到任何可以帮助我完成此任务的东西。 最佳答案 来自RailsActiveSupport::TimeZonedocs:TheversionofTZInfobundledwithActiveSupportonlyincludesthedefinitionsnecessarytosupportthezonesdefinedb

  9. ruby - 我的 Ruby IRC 机器人没有连接到 IRC 服务器。我究竟做错了什么? - 2

    require"socket"server="irc.rizon.net"port="6667"nick="RubyIRCBot"channel="#0x40"s=TCPSocket.open(server,port)s.print("USERTesting",0)s.print("NICK#{nick}",0)s.print("JOIN#{channel}",0)这个IRC机器人没有连接到IRC服务器,我做错了什么? 最佳答案 失败并显示此消息::irc.shakeababy.net461*USER:Notenoughparame

  10. ruby-on-rails - 连接字符串时如何在 <%=%> block 内输出 html_safe? - 2

    考虑一下:现在这些情况:#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2我需要用其他字符串输出URL。我如何保证&符号不会被转义?由于我无法控制的原因,我无法发送&。求助!把我的头发拉到这里:\编辑:为了澄清,我实际上有一个像这样的数组:@images=[{:id=>"fooid",:url=>"http://

随机推荐