我有那个模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var uniqueValidator = require('mongoose-unique-validator');
var EquipmentSchema = new Schema({
model: { type: String, required: true, unique: true},
price: { type: Number, required: true },
comments: { type: String },
market: { type: mongoose.Types.ObjectId, ref: 'Market', required: true },
category: { type: mongoose.Types.ObjectId, ref: 'Category', required: true },
make: { type: mongoose.Types.ObjectId, ref: 'Make', required: true },
rv: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Rv'}],
});
EquipmentSchema.plugin(uniqueValidator);
module.exports = mongoose.model('Equipments', EquipmentSchema);
此功能保存新项目:
const Equipments = require('./_models/equipment.model');
var equipmentSaver = function(equipment) {
return new Promise((resolve, reject) => {
console.log(equipment);
const equipmentToSave = new Equipments({
_id: equipment.type.model._id,
market: equipment.type.market._id,
category: equipment.type.category._id,
make: equipment.type.make._id,
model: equipment.type.model.name,
price: equipment.economicDetails.price,
comments: equipment.economicDetails.comments,
});
equipmentToSave.save()
.then(result => resolve(result))
.catch(error => reject(error))
});
}
module.exports = equipmentSaver;
我从前面得到那个 JSON:
{
type: {
market: {
_id: '5eb1a63926849bed71155592',
name: 'Healthcare',
icon: 'local_hospital'
},
category: {
_id: '5eb19f080141dbe4b9aebc9a',
name: 'Diagnostico por la imagen',
market: '5eb1a63926849bed71155592'
},
make: {
_id: '5ebd3e107002040000e70e53',
name: 'GE',
category: '5eb19f080141dbe4b9aebc9a'
},
model: {
_id: '5ebd3e167002040000e70e54',
name: 'Voluson S8',
make: '5ebd3e107002040000e70e53'
}
},
economicDetails: {
comments: 'Description',
price: 45000,
used: false
}
}
所有这些_ids
都是由前面创建的,我得到了这两个错误:1。
Error [ValidationError]: Equipments validation failed: _id: Cannot read property 'where' of undefined, model: Cannot read property 'where' of undefined
at ValidationError.inspect
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
message: "Cannot read property 'where' of undefined",
name: 'ValidatorError',
properties: [Object],
kind: 'unique',
path: '_id',
value: 5ebd3e167002040000e70e54,
reason: TypeError: Cannot read property 'where' of undefined
2.
MongooseError [ValidatorError]: Cannot read property 'where' of undefined
at new ValidatorError
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
message: "Cannot read property 'where' of undefined",
name: 'ValidatorError',
properties: [Object],
kind: 'unique',
path: 'model',
value: 'Voluson S8',
reason: TypeError: Cannot read property 'where' of undefined
我不知道为什么。我觉得这与这两个字段的“独特”字符有关,但我不确定它为什么会抛出这个错误......
编辑:我找到了错误的根源。当我EquipmentSchema.plugin(uniqueValidator);
从我的模型中删除它时,它再次正确保存......我在mongoose-unique-validator 的 github上创建了一个问题,但是如果这里有人遇到同样的问题,甚至有一个很棒的解决方案!
谢谢!