【发布时间】:2021-02-08 22:44:23
【问题描述】:
我使用 Mongoose 在 nodeJS 中创建了一个这样的模型:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var plantSchema = new Schema({
plantData: [
{
family: { type: String, default: 'Liliaceae' },
genusObj: {
genus: { type: String, required: 'Please enter the genus plant name' },
tulipGroup: { type: String }, // e.g. Single Early
tulipGroupNumber: { type: Number } // e.g. 1
},
species: { type: String, required: 'Please enter the species plant name' },
commonName: { type: String },
description: { type: String },
mainImage: {},
otherImages: {},
images: {},
}
],
detailsData: [ .... ]
});
module.exports = mongoose.model('plants', plantSchema);
这是我的控制器:
var mongoose = require('mongoose'),
Plant = mongoose.model('plants');
// READ ALL
exports.list_all_plants = function(req, res) {
Plant.find({}, function(err, plants) {
if (err) {
res.send(err);
}
res.json(plants);
});
};
// CREATE
exports.create_new_plant = function(req, res) {
var new_plant = new Plant(req.body);
new_plant.save(function(err, plant_inserted) {
if (err) {
res.send(err);
}
res.json(plant_inserted);
});
};
// READ (probably plantId comes from an _id previously retrieved)
exports.read_a_plant = function(req, res) {
Plant.findById(req.params.plantId, function(err, plant_searched) {
if (err) {
res.send(err);
}
res.json(plant_searched);
});
};
// UPDATE
exports.update_a_plant = function(req, res) {
Plant.findOneAndUpdate(
{
_id: req.params.plantId
},
req.body,
{new: true},
function(err, plant_to_update) {
if (err) {
res.send(err);
}
res.json(plant_to_update);
}
);
};
// DELETE
exports.delete_a_plant = function(req, res) {
Task.remove(
{
_id: req.params.plantId
},
function(err, task) {
if (err) {
res.send(err);
}
res.json({ message: 'Plant successfully deleted' });
}
);
};
最后,我有了这个路由器:
'use strict';
module.exports = function(app) {
var plantList = require('../controllers/plantController');
// plant routes
app.route('/plants')
.get(plantList.list_all_plants)
.post(plantList.create_new_plant);
app.route('/plants/:plantId')
.get(plantList.read_a_plant)
.put(plantList.update_a_plant)
.delete(plantList.delete_a_plant);
我想做的是用 Postman 测试所有这些。
如果我尝试使用GET 方法,只需使用
http://localhost:3000/plants
一切正常:我的意思是,它返回一个空数组(mongodb 已启动并运行,一切都已设置)。
现在我想尝试用 Postman 插入一个新元素:我在 body 下选择了 POST 和 x-www-form-urlencoded。必需的属性是 plantData{genusObj{genus}} 和 plantData{species} :由于我对 postman 和 mongodb 都很陌生,如何在 postman 中输入子元素以创建新的 Plant ?
只有KEY和VALUE选项,不知道怎么写像plantData->genusObj->genus这样的子键。
P.S.:欢迎提出关于数据模型的建议,我尝试建立一个通用植物数据库,但面向郁金香(所以通常我可以输入郁金香,但如果我需要输入其他内容,我可以)。
【问题讨论】: