【问题标题】:Trying to save nested document in MongoDB using mongoose on Nodejs尝试在Nodejs上使用猫鼬将嵌套文档保存在MongoDB中
【发布时间】:2020-09-18 14:56:01
【问题描述】:

我试图将地址保存为以下格式的嵌套文档

在客户端,我以以下格式发送数据:

const address = JSON.stringify( { addressline1:form.addressline1.value, addressline2:form.addressline2.value, city: form.city.value, state: form.state.value, pincode:form.pincode.value } );

const res = await fetch('/candidate/contact-details',{
                method: 'POST',
                body: JSON.stringify( { address } ), 
                headers: {
                    'CSRF-Token': csrfToken,
                    'Content-Type': 'application/json'
                }
            });

在服务器端:

module.exports.contactdetail_post = async (req,res) => {

    const token = req.cookies.jwtauthtoken;
    const { address} = req.body;

    try{
        const contactdetail = await ContactDetail.create({ address});
        await PersonalDetail.findOneAndUpdate(
            { candidate: await getUserId(token)}, // find a document with that filter
            {address}, // document to insert when nothing was found
            {upsert: true, new: true, runValidators: true}, // options
            function (err, doc) { // callback
                if (err) {

    console.log({address});
                    const errors = handleErrors(err);
                } else {
                    res.status(200).json({success: 'saved'});
                }
            }
        );
        res.status(200).json({ success: 'Success' });
    }
    catch(err){
        console.log(err);
        const errors = handleErrors(err);
        res.status(406).json({errors});
    }




}

MySchema 如下所示: 这是联系人详细信息的架构。

const contactdetailSchema = new mongoose.Schema({
    address: {
        addressline1: {
            type: String,
            required: [true, 'Please enter your address'],
            minlength:200
        },
        addressline2: {
            type: String,
            minlength:200
        },
        city: {
            type: String,
            required: [true, 'Please selet your city']
        },
        state: {
            type: String,
            required: [true, 'Please select your state']
        },
        pincode: {
            type: Number,
            required: [true, 'Please enter your Pincode'],
            minlength:6
        }
    },
    candidate: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
});

我的控制台输出:

在 processTicksAndRejections (internal/process/task_queues.js:79:11) { 属性:[对象], 种类:'必需', 路径:'address.addressline1', 值:未定义, 原因:未定义, [符号(猫鼬:validatorError)]:真 } }, _message: '验证失败' }

所有参数(addressline2、city、state、pincode)都会显示此错误

【问题讨论】:

  • 我没有看到您在代码中的任何地方解析 JSON。您在客户端对其进行字符串化,但如果您这样做,则需要在服务器上对其进行 JSON.parse() 处理。理想情况下,您根本不应该对其进行字符串化。您收到的错误是有效的,因为服务器只看到一个大字符串而不是它所期望的 JSON 数据。
  • 我在地址上使用了 JSON.parse 并在正文上对其进行了字符串化,但它显示以下错误。 Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1. 你能具体指定修改代码的位置以获得正确的输出吗?
  • 嘿,感谢您的帮助。它在我更改 findOneAndUpdate() 中的代码 { address: JSON.parse(address) } 后起作用。

标签: javascript node.js mongodb express mongoose-schema


【解决方案1】:
 await PersonalDetail.findOneAndUpdate(
            { candidate: await getUserId(token)}, // find a document with that filter
            {address: JSON.parse(address) }, // This line is changed 
            {upsert: true, new: true, runValidators: true}, // options
            function (err, doc) { // callback
                if (err) {

    console.log({address});
                    const errors = handleErrors(err);
                } else {
                    res.status(200).json({success: 'saved'});
                }
            }
        );

像这样更改我的代码可以正常工作。其他代码不变

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 2015-09-06
    • 1970-01-01
    • 2017-02-25
    • 2014-02-10
    • 2017-06-12
    • 2018-10-13
    相关资源
    最近更新 更多