node.js - 填充 Mongoose 的条件

标签 node.js mongodb mongoose

我有如下的电影预订数据

电影订单架构

 {
    "movie_id": "5d64fb7975214a183bf10f5b",
    "variant_id": "5d64fda8fc7f911a77afd55c",

 }

和如下的电影架构数据

{  
   "_id":"5d64fb7975214a183bf10f5b",
   "description":"Sahoo movie ",
   "options":[  

   ],
   "variants":[  
      {  
         "enabled":true,
         "_id":"5d64fda8fc7f911a77afd55c",
         "variant_name":"",
         "regular_price":345,
         "sale_price":125,
         "stock_quantity":45,
      },
      {  
         "enabled":true,
         "_id":"5d661c8181a4572a27f048dd",
         "variant_name":"",
         "regular_price":120,
         "sale_price":50,
         "stock_quantity":10,
      }
   ],

   "on_sale":false,
   "variable":true
}

现在我正在尝试查询电影订单

let data = await MovieOrder.find().populate(movie_id)

但它提供了所有变体的电影详细信息。但我在这里寻找的是

In the movie order what is the variant_id is present based on that I need to populate the movie with variant based on that variant id on the movie order

注意:结果应该是,电影订单架构中的 variant_id 等于电影架构中的变体 id

希望大家理解我的问题,请给我解决方案

最佳答案

按照您的架构设计方式,很难填充以电影顺序中的 variant_id 来过滤电影变体数组 因为这不是填充的工作原理。

为了正确使用填充,您必须更改电影架构,将变量数组作为 ref 更改为 变体模型。例如,您的架构定义需要类似于

架构定义

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const variantSchema = new Schema({
    enabled: Boolean,
    variant_name: String,
    regular_price: Number,
    sale_price: Number,
    stock_quantity: Number
})

const Variant = mongoose.model('Variant', variantSchema)

const movieSchema = new Schema({
    description:  String,
    options:   [String],
    variants: [{ type: 'ObjectId', ref: 'Variant' }],
    on_sale: Boolean,
    variable: Boolean
})

const Movie = mongoose.model('Movie', movieSchema)


await MovieOrder.find().populate('movie_id variant_id')

这样您的查询只返回电影及其所需的变体。

<小时/>

但是,如果当前架构设计保持不变,您可以使用 $lookup在聚合管道中执行填充,然后使用 $filter 过滤结果数组在与 MovieOrder 模型中的 variant_id 字段匹配的变体上:

await MovieOrder.aggregate([
    { '$lookup': {
        'from': 'movies',
        'localField': "movie_id",    // field in the movieorders collection
        'foreignField': "_id",  // field in the movies collection
        'as': "movie"
    } },
    { '$addFields': { 
        'movie': { '$arrayElemeAt': ['$movie', 0 ] }
    } },
    { '$addFields': { 
        'movie.variants': { 
            '$filter': {
                'input': '$movie.variants',
                'cond': { '$eq': ['$variant_id', '$$this._id'] }
            }
        }
    } },
]).exec()

关于node.js - 填充 Mongoose 的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57704585/

相关文章:

node.js - 告诉 Mongoose 使用哪个数据库 - 在 Node.js Express 应用程序中

node.js - 使用 Mongoose 使用 arrayFilters 查找

node.js - 通过 Cloudflare 获取 NODE.JS 上的客户端 IP

node.js - 将 Passport-facebook 与 ReactJS 和 Node.js 一起使用

linux - 在 Centos 上运行 Robomongo

node.js - 在 mongodb select 中使用偏移量和限制

node.js - Angular 2+ 中客户端和服务器之间的通信

node.js - 我可以在模块外使用 NestJS Config Service 吗?

javascript - 传单和 MongoDB 半径

java - 配置 MongoDB 写入关注超时?