微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在猫鼬中保存对象数组?

如何解决如何在猫鼬中保存对象数组?

嗨,我有一组看起来像这样的对象

[{
             "id": 0,"name": "Del Vecchios | Italian Food | Asheville,NC","domain": "delvecchiositalian.com","email": "eat@delvecchiositalian.com","phone": "828-258-7222",},{
             "id": 1,"name": "DeRango's Pizza Palace | Italian Restaurant | Racine,WI","domain": "derangos.com","email": "info@derangospizzapalace.com","phone": "262-639-4112",{
             "id": 2,"name": "Michigan's Premier Flooring Installation Services | D.E. McNabb","domain": "demcnabb.com","email": "no email","phone": "(248) 587-1500",}]

我想将它存储在我的 mongo 数据库中,但我不知道如何制作架构,我的实际架构看起来像这样

const mongoose = require("mongoose");

const infoSchema = new mongoose.Schema(
    {
        info: {
            type: String,trim: true,required: true,maxlength: 3200
        }
    },{ timestamps: true }
);

module.exports = mongoose.model("ScrapedInfo",infoSchema);

这是保存数据的控制器

router.post('/stored',(req,res) => {
        const info = new ScrapedInfo(req.body)
        info.save((err) => {
                if (err) {
                    console.log(err+"error")
                }
                else{
                        console.log('saved')
                }
            });   
});

不知道我是否在控制器中犯了一个错误,对我来说似乎很好,但是我每次运行控制器的按钮时,都会出现错误 ValidationError: info Path info is required

解决方法

当尝试使用 mongoose 更新对象数组时,您必须使用 markModified(path) 方法告诉 MongoDB 有待处理的更改。在此之后,您将不得不调用 save() 方法。

示例 我们将模式的 passwordsArr 部分作为对象数组。

// passwordsArr 已修改

// 将路径标记为有更改写入数据库 user.markModified('passwordsArr');

// 现在保存文档 user.save(function (err,user) { if (err) return next(err);

,

您的架构应如下所示。 “Path info is required 错误”是由 Schema 中不存在键“info”引起的。

    const mongoose = require('mongoose')
    const Schema = mongoose.Schema
    
    // Schema
    const infoSchema = new Schema(
        {
            name: {
                type: String,required: true,},domain: {
                type: String,required: true
            },email: {
                type: String,phone: {
                type: String,required: true
            }
    },{ timestamps: true }
)

// Model
module.exports = mongoose.model('Info',infoSchema)

如果你想保存一个数组,你的“信息”键应该是这样的:

info: {
            type: Array,trim: true,maxlength: 3200
        }

其中“类型”是数组而不是字符串。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?