你好
我有这个猫鼬模式(我知道那里有问题),重要的位是" 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留为空,然后稍后添加,因为它只是一个对象,但是没有任何可行的,对这里有什么问题的想法?
预先感谢!
您可以留下ID以及区域的名称属性,因为您是在引用区域。
const mongoose = require('mongoose');
const destination = new mongoose.Schema({
name: { type: String, required: true },
flag: String,
creationDate: { type: Date, default: Date.now },
region: {type: mongoose.Schema.Types.ObjectId, ref: 'Region' });
module.exports = mongoose.model('Destination', destination);
,然后在您的添加方法中:
exports.destination_create = async(req,res)=>{
const region = await Region.findOne({name: req.body.region});
const destination = new Destination({
region: region._id,
name: req.body.name,
flag: req.body.flag
})
await destination.save();
res.redirect('/destination');
}
我有点找到了一个解决方案,我说有点不确定它的效率是在内存的有效效率,而是:
模型目标已更改:
region: { type: mongoose.Schema.Types.ObjectId, ref: 'Region' },
,然后我所做的就是" 深度填充"区域查询:
Regions.find({})
.select('_id name image countries')
.populate({
path: 'countries',
model: 'Destination',
populate: {
path: 'cities',
model: 'City'
}
}).then(...).catch(...);