node.js - 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)
}
});
});
我很感激任何帮助!
解决方案
从您的猫鼬模式中,您将“biddingGroup”指定为一个字符串数组,但您实际得到的(基于您的控制台输出)是一个对象数组数组,每个对象都应该有一个名为bidderId的属性,这是一个字符串。
要实现与您在 console.log 中获得的架构相匹配的架构,您可以执行以下操作:
const postSchema = new mongoose.Schema({
...
biddingGroup: [[{bidderId: String}]],
...});
推荐阅读
- ruby-on-rails - Rails - Mongoid:生产和开发之间的缓慢问题
- tensorflow - 在远程图中查找占位符和其他张量
- c - 如何修复此代码,以便它可以测试字符旁边的整数?
- python-3.x - 使用pyinstaller创建exe时获取attributeerror'str'对象没有属性'items'
- javascript - 在外部范围内的变量上使用 await 内联
- node.js - 我的 node.js 应用程序正在运行,但无法通过服务器 ip 访问它
- angular - 将组件导入角度 7 中的另一个组件时出错
- c# - 在 c# 中进行 mysqldump 备份不会检索数据
- java - Launch4J 插件创建一个 EXE(连同 JAR),但 EXE 在 Spring boot 中找不到主类
- c# - 从未收到 Xamarin ios 应用程序发送的电子邮件