如何在猫鼬中转换为字符串?

时间:2019-09-21 19:23:57

标签: javascript mongoose mongoose-schema

我在猫鼬中有一个制造商架构,其中一些数据存储在mongo中。我的目标是能够通过表格来编辑制造商的名称。但是更改名称并单击提交时出现以下错误。

  

制造商验证失败:_id:在路径“ _id”的值“ ['example','example edited']”的转换为字符串失败

我了解到_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 %>

1 个答案:

答案 0 :(得分:0)

我还没有测试过,但是_id在mongodb中不是字符串,它是一种特殊的数据类型,我不记得这个名字了。因此,当您尝试将其转换为字符串时,会感到不安并抛出错误。在我编写的应用程序中(当然有很多剪切和粘贴),我从未定义过_id,因此没有遇到任何问题。

我认为,如果您从架构中删除_id,那么您将获得所需的内容。

如果要使Manufacturer.id为主键,则必须明确地说出来,不要将其命名为_id

我将名称字段添加到制造商模式。您可以将其设为主键,也可以在名称上创建索引以加快访问速度

相关问题