【问题标题】:How to populate without _id in mongoose with array of foreign key?如何使用外键数组在没有 _id 的猫鼬中填充?
【发布时间】:2021-01-29 12:50:23
【问题描述】:

我知道我可以在没有 _id 的情况下在 mongoose 中使用 virtual 来填充。 但是我的情况是这样的:

const storeSchema = new mongoose.Schema({
  store_id: Number,
  store_name: String,
  cart_tokens: [String],
})

const cartSchema = new mongoose.Schema({
  cart_token: String,
  items: { type: Array },
})

我在 store 模式中的 cart_tokens 是一个数组而不是一个值。 我希望 store 的结果是这样的:

{
   store_id: xxx,
   store_name: xxx,
   carts:[
      {
          cart_token: xxx,
          items: [...],
      },
      {...},
      {...}
   ]
}

可以这样做吗?

【问题讨论】:

    标签: node.js mongodb mongoose populate mongoose-populate


    【解决方案1】:

    这会起作用:

    const mongoose = require('mongoose');
        const Schema = mongoose.Schema;
        
        let cartSchema = new Schema({
          cart_token: String,
          items: { type: Array },
        })
        
        
        let storeSchema = new Schema({
          store_id: Number,
          store_name: String,
          cart_tokens: [cartSchema]
        });
        
        module.exports = mongoose.model('Cart', cartSchema);
    

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2014-03-31
      • 2017-12-06
      • 2020-07-25
      • 2016-06-11
      • 2020-01-30
      • 2020-09-13
      • 2014-04-19
      • 1970-01-01
      相关资源
      最近更新 更多