【发布时间】:2020-04-17 21:06:09
【问题描述】:
感谢您点击我的问题..
我在mongodb中有两个schema,citySchema和destinationSchema。我想建立一对多的关系。每个目的地都有一个城市,而这个城市有很多目的地。
这是我的destinationSchema
var mongoose = require("mongoose");
var destinationSchema = new mongoose.Schema({
name: String,
image: String,
description: String,
city: {
type: mongoose.Schema.Types.ObjectId,
ref: "City"
}
});
module.exports = mongoose.model("Destination", destinationSchema);
这是citySchema
var mongoose = require("mongoose");
var citySchema = new mongoose.Schema({
name: String,
image: String,
description: String,
destinations: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Destination"
}
]
});
module.exports = mongoose.model("City", citySchema);
这是创建新目的地
的发布路线router.post("/", function(req, res) {
var name = req.body.name;
var image = req.body.image;
var description = req.body.description;
var city = req.body.city;
var newDestination = {
name: name,
image: image,
description: description,
city: city
};
Destination.create(newDestination, function(err, newCreatedDestination) {
if (err) {
console.log(err);
} else {
res.redirect("/admin/destinations");
}
});
});
这是我创建新目的地
的表单<select name="city">
<% cities.forEach(function(city) { %>
<option value=<%=city._id%> > <%= city.name %> </option>
<% }) %>
</select>
它工作正常。但我希望在创建新目的地时,将当前目的地 ID 推送到城市架构(目的地数组)。
对不起,我的英语不好。我感谢您的每一个回答和建议。还有谢谢???
【问题讨论】:
标签: node.js mongodb express mongoose ejs