[英]Issue implementing a Mongoose PUT for a custom object into a complex schema
[英]Posting Mongoose Complex Schema
你好
我有這個Mongoose Schema(我知道那里有問題),重要的是它的“ 區域 ”部分。
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以及區域的name屬性,因為您正在引用Region。
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(...);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.