我试图用子文档数组保存模式时遇到问题 . 子文档保存为空白 . 请帮我 .
谢谢
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 =接触;
route const express = require('express'); const router = express.Router(); const Contact = require('../ models / contacts'); // get contact router.get('/ contacts',(req,res,next)=> {Contact.find(function(err,contacts){if(err)throw err; res.json(contacts);}) }); //添加联系人(form1)router.post('/ contact',(req,res,next)=> {let newContact = new Contact({first_name:req.body.first_name,last_name:req.body.last_name,phone :req.body.phone,clg_name:req.body.clg_name,class_name:req.body.class_name,roll_number:req.body.roll_number});
newContact.save((ERR,联系)=>
{
如果(ERR)
{
res.json({msg:“联系人不保存”});
}
其他{
的console.log(触点);
res.json({msg:“联系人已保存”});
}
});
});
// detete contact router.delete('/ contact /:id',(req,res,next)=> {Contact.remove({_ id:req.params.id},function(err,result){if(err) ){res.json(err);} else {res.json(result);}});}); module.exports =路由器; mongodb数据库
{
> "_id" : ObjectId("5b3c6e4ea380651ebcf762ea"),
> "first_name" : "ang",
> "last_name" : "raw",
> "phone" : "123456",
> "meta" : [
>
> ],
> "__v" : NumberInt(0)
> }
1 回答
我认为req.body中存在问题,也不打印req.body.createdObject,因为正文不包含它而不分配 .
尝试创建一个新变量并将body的值放入其中,然后使用新的Contact(newVariable)进行保存 .