【问题标题】:saving array type value inside mongodb schema using node js使用节点js在mongodb模式中保存数组类型值
【发布时间】:2021-11-12 07:36:45
【问题描述】:

我正在尝试将数组数据放入我的架构中,但它没有显示在我的 mongodb 架构中

ownerSchema.js

var ownerSchema = Schema({
    ownerId   : String,
    fname     : String,
    lname     : String,
    shopPlace : { 
                  type: Schema.Types.ObjectId,
                  ref: 'Shop'
                },
    shopType    String
});
var Owner = mongoose.model('Owner', ownerSchema);

shopSchema.js

var shopSchema = Schema({
    _id       : String,
    shopName  : String,
    location  : String,
    startDate : Date,
    endDate   : Date
});
var Shop  = mongoose.model('Shop', shopSchema);

因为我在 shopType 内发送数组格式数据,但它没有显示架构内的任何数据

当我从邮递员发送此邮件时,我的格式如下所示

{
 "ownerId"   : "Own001",
 "fname"     : "Tom",
 "lname"     : "jerry",
 "shopPlace" : {
                 "shopName" : "Juice Center",
                 "location" : "Mumbai",
               },
 "shopType"  : ["Juice","vegetables"]
}

但是当我发送此数据时,只有 ownerId、fname、lname、shopPlace 显示在架构内部,我的 shopType 数据不可见

const addTask = async (req, res) => {
  const { shopName, location } = req.body.shopPlace;
  const shopDetails = new Shop({
      shopName,
      location,
    });
    await shopDetails.save();

    const { ownerId, fname, lname, shopType } = req.body;
    const ownerDetail = new Owner({
      ownerId,
      fname,
      lname,
      shopType,
      shopPlace: shopDetail._id,
    });
    await shopDetail.save();
};

我想以数组格式存储 shopType 但它甚至没有显示在我的架构中

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-query


    【解决方案1】:

    像这样改变你的架构

    var ownerSchema = Schema({
        ownerId   : String,
        fname     : String,
        lname     : String,
        shopPlace : { 
                      type: Schema.Types.ObjectId,
                      ref: 'Shop'
                    },
        shopType :   [{
        type: String
    }]
    });
    var Owner = mongoose.model('Owner', ownerSchema);
    

    【讨论】:

    • 嗨,但是当我发送我的数据时,它向我显示了一个像这样的空数组"shopType": []
    • 你能登录shopTypereq.body
    • 在日志中是的,我的价值是["juice","vegetable"]
    • cost 更改为 let 例如,` const { ownerId, fname, lname, shopType } = req.body;`
    • 欢迎您:)
    猜你喜欢
    • 2016-02-13
    • 2018-06-02
    • 2021-06-08
    • 2020-10-22
    • 2019-02-20
    • 2022-01-24
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多