我在猫鼬中有一个制造商模式,一些数据存储在mongo中。我的目标是能够通过表单编辑制造商的名称。但是当更改名称并单击提交时,我收到以下错误。
制造商验证失败:_id:转换为字符串失败的值"['example','example编辑']"在路径"_id"
我知道_id有某种冲突,因为它是由mongo自动创建的。但是在这种情况下,我需要使用_id作为对象名称。
这是我的猫鼬图式
var manufacturerSchema = mongoose.Schema({
// The _id property serves as the primary key. If you don't include it
// the it is added automatically. However, you can add it in if you
// want to manually include it when creating an object.
// _id property is created by default when data is inserted.
_id: {"type" : String},
mfgDiscount: {"type" : Number}
},
{ // Include this to eliminate the __v attribute which otherwise gets added
// by default.
versionKey: false
});
这里是更新
async update(editedObj) {
// Load the corresponding object in the database.
let manufacturerObj = await this.getManufacturer(editedObj.id);
// Check if manufacturer exists.
if(manufacturerObj) {
// Manufacturer exists so update it.
let updated = await Manufacturer.updateOne(
// Set new attribute values here.
{$set: { _id: editedObj._id }});
// No errors during update.
if(updated.nModified!=0) {
response.obj = editedObj;
return response;
}
更新功能
// Receives posted data that is used to update the item.
exports.Update = async function(request, response) {
let manufacturerID = request.body._id;
console.log("The posted manufacturer id is: " + manufacturerID);
// Parcel up data in a 'Manufacturer' object.
let tempManufacturerObj = new Manufacturer( {
_id: manufacturerID,
id: request.body._id,
});
// Call update() function in repository with the object.
let responseObject = await _manufacturerRepo.update(tempManufacturerObj);
// Update was successful. Show detail page with updated object.
if(responseObject.errorMessage == "") {
response.render('Manufacturer/Detail', { manufacturer:responseObject.obj,
errorMessage:"" });
}
// Update not successful. Show edit form again.
else {
response.render('Manufacturer/Edit', {
manufacturer: responseObject.obj,
errorMessage: responseObject.errorMessage });
}
};
这是表格
<% layout('../layouts/mainlayout.ejs') -%>
<form action="/Manufacturer/Update" method="POST">
<input type='hidden' name="_id" value= <%= manufacturer._id %> /> <br/>
<input type='text' name="_id"
value="<%= manufacturer._id ? manufacturer._id : '' %>" /><br/>
<input type="submit" value="Submit">
</form>
<%= errorMessage %>
我还没有测试过这个,但是_id不是mongoDB中的字符串,它是一种特殊的数据类型,我不记得它的名字了。所以当你试图将它转换为字符串时,会出现错误。在我编写的应用程序中(当然有很多剪切和粘贴),我从未定义过_id所以没有遇到任何问题。
我认为如果你把_id从模式中去掉,你会得到你想要的。
如果你想让manufacturer.id主键,那么你必须明确地说,不要称之为_id
我会在制造商模式中添加一个名称字段。您可以将其作为主键或在名称上创建索引以加快访问速度