【发布时间】:2019-08-10 06:52:31
【问题描述】:
你好
我有这个 Mongoose Schema(我知道那里有问题),重要的是它的“region”部分。
const mongoose = require('mongoose');
const destination = new mongoose.Schema({
name: { type: String, required: true },
flag: String,
creationDate: { type: Date, default: Date.now },
region: { id: { type: mongoose.Schema.Types.ObjectId, ref: 'Region' }, name: String },
}, {strict: true});
module.exports = mongoose.model('Destination', destination);
我使用这个表格发帖:
<form action="/destinations" method="post">
<div class="form-group">
<label for="destination[name]">Name</label>
<input class="form-control" type="text" name="destination[name]" placeholder="Destination name...">
</div>
<div class="form-group">
<label for="destination[name]">Flag</label>
<input class="form-control" type="text" name="destination[flag]" placeholder="Destination flag...">
</div>
<div class="form-group">
<label for="destination[region]">Region</label>
<select class="form-control mb-4" name="region[name]]">
<option selected disabled hidden>Choose a region</option>
<% allRegions.forEach(region => { %>
<option value="<%= region.name %>">
<%= region.name %>
</option>
<% }); %>
</select>
</div>
<button class="btn btn-primary btn-block" type="submit">Add</button>
</form>
所有数据都已正确发布到处理它的 Node.js 文件,但是我找不到保存“区域 ID”的方法,这就是现在的处理方式:
exports.destinations_create = (req, res) => {
req.body.destination.region = { name: req.body.region.name };
Destination.create(req.body.destination)
.then(newDestination => {
Regions.findOne({name: req.body.region.name})
.then(foundRegion => {
newDestination.region.id = foundRegion._id;
foundRegion.countries.push(newDestination._id);
foundRegion.save();
});
res.redirect('/destinations');
})
.catch(err => res.redirect('/'));
}
我想我可以将 id 留空,然后再添加它,因为它只是一个对象,但没有任何作用,你知道这里有什么问题吗?
提前致谢!
【问题讨论】:
标签: javascript node.js mongodb mongoose schema