如何解决如何在猫鼬中保存对象数组?
嗨,我有一组看起来像这样的对象
[{
"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 举报,一经查实,本站将立刻删除。