二级字符串未传递到MongoDB,但是二级数字和日期为

时间:2018-12-14 15:05:52

标签: mongodb express mongoose mongoose-schema

我正在尝试将项目/ POST到MongoDB数据库中,但是其中五件事中只有三件事正在经历,或者当“ required:true”标志打开时,它会收到验证错误。

服务器/模型/item.js

var mongoose = require('mongoose');

var Item = mongoose.model('Item', {
  category: {
    type: String,
    minlength: 1,
    trim: true,
    required: true,
  },
  product: {
    title: {
      type: String,
      minlength: 1,
      trim: true,
      required: true
    },
    quantity: {
      type: Number,
      default: 1,
      required: true
    },
    added: {
      type: Date,
      default: Date.now
    },
    description: {
      type: String,
      minlength: 1,
      trim: true,
      required: true
    }
  }
});

module.exports = {Item};

server / db / mongoose.js

var mongoose = require('mongoose');

mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/Website', { useNewUrlParser: true });

module.exports = {mongoose};

server / server.js

const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');

const hbs = require('hbs');
const fs = require('fs');

var {mongoose} = require('./db/mongoose');
var {Item} = require('./models/item');

const port = process.env.PORT || 3000;
var app = express();
// console.log(__dirname);

app.use(bodyParser.json());

hbs.registerPartials(__dirname + '/../views/partials')
app.set('view engine', 'hbs');

app.use((req, res, next) => {
    var now = new Date().toString();
    var log = `${now}: ${req.method} ${req.url}`;

    console.log(log);
    fs.appendFile('server.log', log + '\n', (err) => {
        if (err) {
            console.log('Unable to append to server.log.');
        }
    });
    next();
});

app.use(express.static(__dirname + '/../public'));

hbs.registerHelper('getCurrentYear', () => {
    return new Date().getFullYear()
});

// POST ROUTES

app.post('/equipment', (req, res) => {
    console.log("Post command received");
    console.log("This is the category: " + req.body.category);
    console.log("This is the title: " + req.body.product.title);
    console.log("This is the quantity: " + req.body.product.quantity);
    console.log("This is the description: " + req.body.product.description);

    var item = new Item({
        category: req.body.category,
        title: req.body.product.title,
        quantity: req.body.product.quantity,
        description: req.body.product.description
    });
    console.log(item);

    item.save().then((doc) => {
        console.log(doc);
        res.send(doc);
    }, (e) => {
        res.status(400).send(e);
    });
});



app.all('*', function(req, res) {
  res.render("error.hbs");
});

app.listen(port, () => {
  console.log(`Started on port ${port}`);
});

module.exports = {app};

最后,我正在尝试通过邮递员/ POST到/ equipment

{
    "category": "Lighting",
    "product": {
        "title": "Litepanel Duo Traveller Kit",
        "quantity": 1,
        "description": "A two light LED panel kit, containing one spot and one flood Litepanel 1x1 panel, with all drop in filters needed. Incldues two stands, power leads and adaptors, v-lock battery plates, and carry case."
    }
}

在item.js中删除“ required:true”标记时,POST可以运行,但是“ product.title”和“ product.description”不会传递给数据库。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

猫鼬save函数,它将使用JSON对象并将其存储在数据库中。要将数据保存到数据库中,您需要创建一个模型的新实例,该实例要早些创建,并且应采用与定义的格式相同的格式。

根据您的商品模型,尝试以下操作:

var item = new Item({
        category: req.body.category,
        "product.title": req.body.product.title,
        "product.quantity": req.body.product.quantity,
        "product.description": req.body.product.description
    });