【问题标题】:I got an empty array in sub document array saving using mongoose ( MEAN stack)我在使用猫鼬(MEAN 堆栈)保存的子文档数组中得到了一个空数组
【发布时间】:2018-11-29 11:36:55
【问题描述】:

我在尝试使用子文档数组保存架构时遇到问题。子文档保存为空白。请帮帮我。

谢谢

schema.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var contactSchema = new Schema({
    first_name:String,
    last_name:String,
    phone:String,   
    meta:[{
        clg_name: String,
        class_name:String,
        roll_number: String
    }]
});

var contact=mongoose.model('contact',contactSchema); module.exports=联系人;

路线

const express= require('express');常量路由器= express.Router(); const Contact= require('../models/contacts');

//获取联系人 router.get('/contacts',(req,res,next)=>{ Contact.find(function(err,contacts){ if (err) 抛出错误; res.json(联系人); })
}); //添加联系人(form1) router.post('/contact',(req,res,next)=>{ 让新联系人=新联系人({ 名字:req.body.first_name, 姓氏:req.body.last_name, 电话:req.body.phone, clg_name:req.body.clg_name, 类名:req.body.class_name, roll_number:req.body.roll_number

    });

    newContact.save((err,Contact)=>
    {
        if(err) 
        {

            res.json({msg:"contact does not save"});
        }
            else{
                console.log(Contact);
                res.json({msg:"contact is saved"});
            }
    });

});

//detete 联系人 router.delete('/contact/:id',(req,res,next)=>{ Contact.remove({_id:req.params.id} ,function(err,result){ 如果(错误) { res.json(err); } 其他{ res.json(结果); } }); });

module.exports=路由器;

mongodb数据库

{ 
    >         "_id" : ObjectId("5b3c6e4ea380651ebcf762ea"), 
    >         "first_name" : "ang", 
    >         "last_name" : "raw", 
    >         "phone" : "123456", 
    >         "meta" : [
    >     
    >         ], 
    >         "__v" : NumberInt(0)
    >     }

database image///form input

【问题讨论】:

  • 请不要将您的源代码发布为图像。在你的问题中写下代码并用 4 个空格缩进。
  • 获取源代码请点击2..
  • 没有。那是源代码的图像。粘贴源代码的文本并缩进4个空格。
  • 我编辑了这个问题......现在你检查一下。
  • 你刚刚破坏了代码的格式。不可读的代码使您的问题难以回答。

标签: node.js mongodb mongoose mean-stack


【解决方案1】:

我认为 req.body 有问题,也不要打印 req.body.createdObject 因为 body 不包含它而没有分配。

尝试创建一个新变量并将 body 的值放入其中,然后使用 new Contact(newVariable) 保存。

【讨论】:

    猜你喜欢
    • 2015-08-16
    • 2018-03-20
    • 1970-01-01
    • 2015-09-03
    • 2016-01-24
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多