首页 > 解决方案 > Mongodb不在文档中存储字符串数组

问题描述

如果我添加console.log(req.body.biddingGroup)到我的 PUT 方法,那么它会返回

[ [ { bidderId: '5dd5b31213372b165872bf5b' } ] ]

因此我知道该值正在正确传递,但是如果我添加该行biddingGroup: req.body.biddingGroup

出价永远不会更新到 mongodb。如果我删除那一行,那么出价就会更新。

不知道为什么它没有被传递给 mongodb。我也试过monogoose模型

biddingGroup: [{
    type: String
}]

但这返回了错误

Cast to string failed for value "{}" at path "biddingGroup"

猫鼬模式


const mongoose = require('mongoose');


const postSchema
 = mongoose.Schema({
title: {type: String},
startingBid: {type: String},
bidderId: {type: String},
currentBid: {type: String},
lastBidTimeStamp: {type: Date},
increments: {type: String},
shippingCost: {type: String},
auctionType: {type: String},
buyItNow: {type: String},
snipingRules: {type: String},
auctionEndDateTime: {type: String},
biddingGroup: {bidderId: {type: String}},
currentBid: { type: String, require: true },
lastBidTimeStamp: { type: Date, required: true },
creator: { type: mongoose.Schema.Types.ObjectId, ref: "User"},
 });


const Auction = mongoose.model('Listing', postSchema);


module.exports = Auction;

应用程序.js

app.put('/api/listings/:id', (req, res) => {
  console.log(req.body.biddingGroup);
  Post.findByIdAndUpdate({ _id: req.params.id },
    {
      currentBid: req.body.currentBid,
      lastBidTimeStamp: Date.now(),
      bidderId: req.body.bidderId,
      biddingGroup: req.body.biddingGroup,
      auctionEndDateTime: req.body.auctionEndDateTime
    }, function (err, docs) {
      if (err) res.json(err);
      else {
        console.log(docs)
      }
    });
});

我很感激任何帮助!

标签: node.jsmongodbexpressmongoose

解决方案


从您的猫鼬模式中,您将“biddingGroup”指定为一个字符串数组,但您实际得到的(基于您的控制台输出)是一个对象数组数组,每个对象都应该有一个名为bidderId的属性,这是一个字符串。

要实现与您在 console.log 中获得的架构相匹配的架构,您可以执行以下操作:

const postSchema = new mongoose.Schema({
    ...
    biddingGroup: [[{bidderId: String}]],
    ...});

推荐阅读