如何使用外键数组在猫鼬中不使用_id进行填充?

问题描述

我知道我可以在没有_id的情况下使用虚拟的猫鼬填充。 但是我的情况是这样的:

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

我在商店架构中的cart_tokens是一个数组,而不是一个值。 我希望存储的结果是这样的:

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

可以这样做吗?

解决方法

这将起作用:

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...