我有一个post路径,它接收来自express应用程序中PUT请求的数据,该应用程序旨在根据提交的表单输入更新mongoose文档."基本"模型是Profile
,我有两个discriminator模型Helper
和Finder
,它们有条件地向Profile
模式中添加字段(详见下文).
因此,req.body.profile
将包含不同的字段,这取决于它所关联的鉴别器,但始终包含"基本"模型Profile
中存在的字段(username
、email
、city
、accountType
).
在发送PUT请求之前,Profile
中的文档示例如下所示:
{ jobTitle: '',
lastPosition: '',
email: '',
city: '',
accountType: 'helper',
_id: 5c77883d8db04c921db5f635,
username: 'here2help',
__v: 0 }
这在我看来很好,并表明模型是按照我的意愿创建的(基本字段从Profile
开始,与Helper
模型相关的字段——请参见下面的模型).
我的发帖路由如下:
router.put("/profile/:id", middleware.checkProfileOwnership, function(req, res){
console.log(req.body.profile);
Profile.findOneAndUpdate(req.params.id, req.body.profile, function(err, updatedProfile){
if(err){
console.log(err.message);
res.redirect("/profile");
} else {
console.log(updatedProfile);
res.redirect("/profile/" + req.params.id);
}
});
});
我从表格(console.log(req.body.profile)
)中收到的信息是我希望看到的:
{ accountType: 'helper',
username: 'here2help',
email: 'helpingU@me.com',
city: 'New York',
jobTitle: 'CEO',
lastPosition: 'sales rep'}
但是,在Profile.findOneAndUpdate()
中用req.body.profile
更新文档后,我没有看到我返回的文档更新:
console.log(updatedProfile)
{ jobTitle: '',
lastPosition: '',
email: 'helpingu@me.com',
city: 'New York',
accountType: 'helper',
_id: 5c77883d8db04c921db5f635,
username: 'here2help',
__v: 0 }
因此,我的"基本"模型中定义的字段(即ProfileSchema
中定义的字段-见下文)正在更新(例如city
),但我的鉴别器中的字段没有更新-见下文.
更新的信息清楚地显示在req
中,但没有传播到Profile
型号-How can this be?
我也try 过使用findByIdAndUpdate
,但我得到了同样的结果.
以下是我定义的模式:
Profile-我的"基本"模式:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var profileSchema = new mongoose.Schema({
username: String,
complete: { type: Boolean, default: false },
email: { type: String, default: "" },
city: { type: String, default: "" }
}, { discriminatorKey: 'accountType' });
profileSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Profile", profileSchema);
Finder
var Profile = require('./profile');
var Finder = Profile.discriminator('finder', new mongoose.Schema({
position: { type: String, default: "" },
skills: Array
}));
module.exports = mongoose.model("Finder");
Helper
var Profile = require('./profile');
var Helper = Profile.discriminator('helper', new mongoose.Schema({
jobTitle: { type: String, default: "" },
lastPosition: { type: String, default: "" }
}));
module.exports = mongoose.model("Helper");
这是我第一次try 在mongoose中使用discriminators,所以我很可能设置不正确,这是问题的根源.
如果不清楚,请告诉我,或者我需要补充更多信息.