简体   繁体   中英

Mongodb not storing string array in document

If I add console.log(req.body.biddingGroup) to my PUT method then it returns

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

Therefore I know that the value is being passes properly, but if I add the line biddingGroup: req.body.biddingGroup

the bid never updates to mongodb. If I remove that one line, then the bid updates.

Not sure why it's not being passed to mongodb. I also tried in monogoose model

biddingGroup: [{
    type: String
}]

but that returned the error

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

mongoose schema


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;

app.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)
      }
    });
});

I appreciate any help!

From your mongoose schema you are specifying the "biddingGroup" to be an array of strings , but what you actually get (based on your console output) is an array of arrays of objects , each of those objects then should have a property called bidderId, which is a string.

To achieve a schema that matches what you get in your console.log, you can do the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM