简体   繁体   English

如何在 JavaScript 中使用 Mongoose 动态更新文档?

[英]How to dynamically update documents with Mongoose in JavaScript?

I need to update attributes from a MongoDB document based on the value from the data-target from an HTML object.我需要根据来自 HTML object 的data-target的值更新 MongoDB 文档中的属性。 However, I don't know how to insert its data-target in the JSON.stringify但是,我不知道如何将其data-target插入JSON.stringify

const save = (_id) =>{
    const token = localStorage.getItem('token')
    const saves= document.querySelectorAll(".flaticon-diskette")

    saves.forEach(function(save){

        console.log(`.input-${save.getAttribute("data-target")}`)
        const input = document.querySelector(`.input-${save.getAttribute("data-target")}`)
        var target = save.getAttribute("data-target")

        save.addEventListener('click', () =>{
            fetch(`https://janfa.gharsnull.now.sh/api/auth/edit/${_id}`,{
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    authorization : token,
                },
                body: JSON.stringify( { target : `${input.value}`} ), 
            }).then(console.log("done"))
        })
    })
}

target is supposed to contain the data-target of each save but instead it's read as "target" by JSON.stringify . target应该包含每个savedata-target ,但它被JSON.stringify读取为“目标”。 I tried using a template strings, but it seems like JSON.stringify won't let me use it in the first field.我尝试使用模板字符串,但似乎JSON.stringify不允许我在第一个字段中使用它。 What can I do?我能做些什么?

To update a document using Mongoose you need to use the yourDocumentModel.findByIdAndUpdate() (if it's one document at a time) function.要使用 Mongoose 更新文档,您需要使用 yourDocumentModel.findByIdAndUpdate()(如果一次只有一个文档)function。

If you've installed all the packages as you'll need to do is call the async function to update the document in the DB如果您已经安装了所有软件包,您需要调用异步 function 来更新数据库中的文档

Solved it just by changing body: JSON.stringify( { target: '${input.value}'} ) for body: JSON.stringify( { [target]: '${input.value}'} )只需更改body: JSON.stringify( { target: '${input.value}'} ) for body: JSON.stringify( { [target]: '${input.value}'} )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM