猫鼬在Ref模式中保存对象数组

时间:2018-10-12 12:36:08

标签: node.js mongodb mongoose

我有Parent架构:

const parentSchema = new Schema({
   name: {
   type: String,
  },
 children: [{
    type: Schema.Types.ObjectId,
    ref: "Children"
  }]
})

这是Children模式:

const childrenSchema = Schema({
  name: {
   type: String
  },
  surname: {
   type: String
  }
})

我有一个以下格式的传入用户注册POST请求:

{
 "name": "TEST", 
 "children" : [
    { "name":"test","surname": "test" },
    { "name":"test","surname": "test" }
 ]
}

这是路由器:

 router.post("/register", (req, res, next) => {
  const {name, children} = req.body;
  let newParent = newParent({
    name,
    children
   });
  newParent.save((err, result) => {
    // res.send(result) etc.
  })
 }

这将导致以下错误:

Cast to Array failed for value "[ { name: 'test', surname: 'test' } ]" at path "children"

如何保存所有children并仅将ref个孩子留在_id中,以便以后以后populate Parent的收藏中?

2 个答案:

答案 0 :(得分:0)

父级中的children字段需要一个ObjectId数组,但是您要向其传递不符合该期望的对象数组。请尝试保存子代,获取ID,然后使用这些ID填充父文档中的子代字段。如下所示:

children.save()
.then(results => {

childrenids = []
results.foreach[item => childrenids.push(result._id)]
newParent.children = chilrenids
newParent.save()
.then(results => res.send({results})
})

答案 1 :(得分:0)

  

要将childData保存在Parents中,您需要将第一个孩子的数据保存在children模式中,然后获取childIds并保存到Parent Data中。

工作示例:

let req = {
    "name" : "TEST", 
    "children" : [
       { "name":"test","surname": "test" },
       { "name":"test","surname": "test" }
    ]
   }

   Children.collection.insert(req.children, function (err, docs) {
    if (err){ 
       conasolw.log(err);
    } else {
      var ids =  docs.ops.map(doc=>{ return doc._id});;
      console.log(ids);
      let newParent = Parent({
        name : req.name,
        children : ids
       });
       newParent.save((err, result) => {
         console.log('parent save');
         console.log(err);
         console.log(result);
      })
    }
  });

注意:

  

"mongoose": "^5.3.3"上测试