Create objects with references Node Js and MoongoDB

0

Hello, I have the following data models in mongo db

var mongoose = require("mongoose");
var accountSchema = new mongoose.Schema({
    name: String
});

module.exports = mongoose.model("Account",accountSchema);

A second model

var mongoose = require("mongoose");

var bundleSchema = new mongoose.Schema({
    bundle: String,
    ban: String,
    country: String
});

module.exports = mongoose.model("Bundle",bundleSchema);

and a third model that relates both models

var mongoose = require("mongoose");

var serviceSchema = new mongoose.Schema({    
    service: String,

    account:{         
            type: mongoose.Schema.ObjectId,
            ref: "Account"
        },     
    bundle: {        
                type: mongoose.Schema.Types.ObjectId,
                ref: "Bundle"            
        }
});
module.exports = mongoose.model("Service",serviceSchema);

The problem I have is when creating the object with references it tells me that the following error

  

CastError: Cast to ObjectID failed for value "{account:   5bf32c6e43ff0338c69f20f} "at path" account "

This is the method I try to implement to create the object

router.post("/",function(req,res){     
    var serv = req.body.service;
    var accountName = {name:req.body.accName};
    var bundleName = {bundle:req.body.bdlNumber};

    Account.findOne(accountName,function(err,fAccount){
        if(err){console.log(err)}
        else{

            console.log(fAccount._id);
            var acc = {account:fAccount._id};

           Bundle.findOne(bundleName,function(err,fBundle){
            if(err){console.log(err);}
            else{
                console.log(fBundle._id);
                var bld = {id:fBundle._id };

                var newService = {service:serv,account:acc,bundle:bld}

                Service.create(newService,function(err,newlyCreated){
                    if(err){console.log(err);}
                    else{
                    console.log(fBundle.telco);
                    res.redirect("/services/")
                }})

            }
           })     
        }
    })
})

How do I create the object to later popularize the data of the other objects?

Thanks

    
asked by Marco Marichal 21.11.2018 в 01:47
source

1 answer

0

The problem is in the variable "newService" where you pass an object that has a key account and value acc, the value of acc is not typo "ObjectID" but is of type objecto and in the model you specified that account must be of type ObjectID, to correct it modify the following:

var newService = {service:serv,account:acc.account,bundle:bld}
    
answered by 21.11.2018 в 02:14