我正在使用Mongoose将我的Node.js服务器迁移到OpenShift,并且在我的本地WebStorm内置服务器上无法重现的实时服务器上发生错误。
我收到错误消息:
undefined: {
properties: {
message: "Cannot read property 'options' of undefined"
type: "cast"
}-
message: "Cannot read property 'options' of undefined"
name: "ValidatorError"
kind: "cast"
}
当我尝试将元素推入items
数组并保存时,会发生以下情况:
var listSchema = new mongoose.Schema({
owner: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
name: {type: String, required: true},
items: [
{
name:{
type: String,
required:true
},
quantity:Number,
check: Boolean
}
]
});
有效的本地版本,OpenShift版本使用完全相同的代码。添加新元素的代码是:
var listId = req.params["id"];
if (sessions.verifyToken(userId, token)) {
var data = req.body;
var query = List.findOne({
owner: userId,
"_id": listId
});
query.exec(function(err, list) {
...
//handle error and null (omitted for brevity)
...
list.items.push({ // error thrown here
name: req.body["name"],
quantity: req.body["quantity"],
check: false
});
list.save(function(err, list) {
if (err) {
var message = "Unable save appended list to persistent memory";
console.log(message, err);
res.setHeader("content-type", "application/json");
res.send(JSON.stringify({success: false, message: message, error: err}));
return;
}
res.setHeader("content-type", "application/json");
res.send(JSON.stringify(list));
});
});
我认为可能早期版本的模式添加了一个约束,所以我放弃了lists
集合,但问题并没有消失。
可能导致错误的OpenShift PaaS可能有什么不同?
[编辑]
只是为了好玩,我从items
中删除了所有必填字段,现在错误信息为:
"undefined": {
"properties": {
"message": "Cannot read property 'options' of undefined",
"type": "cast"
},
"message": "Cannot read property 'options' of undefined",
"name": "ValidatorError",
"kind": "cast"
},
"owner": {
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "owner"
},
"message": "Path `owner` is required.",
"name": "ValidatorError",
"kind": "required",
"path": "owner"
}
这似乎表明模型在找到列表并再次保存之间的某处丢失了owner
字段。
[/编辑]
答案 0 :(得分:0)
在OpenShift上,当find
或findOne
模型具有对另一个实体的必需引用时,该字段将不会自动填入。因此,当调用save
时,该领域将失踪。改变
var query = List.findOne({
owner: userId,
"_id": listId
});
到
var query = List.findOne({
owner: userId,
"_id": listId
}).populate("owner");
出于某种原因,这在每个环境中都不起作用。对于某些人来说,要么自动填充参考字段,要么在保存时假设它不变。我不确定是哪一个。