0

I'm using MongoDB with Mongoose, I have to save user data to users collection which contains username, password and company data, *Company data will be having Company name, Address, and website URL Now what I've done is I've created the different schema for company and users

I need to store user data along with the company ID after installing it into the company collection, for ex.

{
  username: "Lorem Ipsum",
  password: "Dolar Sit",
  company: "5c73afcf9a3bde1a40da5184"
}

something like this (Note: That random string is ID of the company data), but I'll send everything in 1 object like below

{
  username: "Lorem Ipsum",
  password: "Dolar Sit",
  company: {
     company_name: "Blah Blah",
     company_address: "Blah Blah Blah",
     company_website: "BlahBlah.com",
  }
}

My user Schema (user.js) is :

const mongoose = require('mongoose');

const Company = require('./company');
Schema = mongoose.Schema

// User Schema
const userSchema = mongoose.Schema({
    username:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    },
    company:{
        type: [{ type: Schema.Types.ObjectId, ref: 'Company' }],
        required: true
    },
    created_on:{
        type: Date,
        default: Date.now
    },
    updated_on:{
        type: Date,
        default: Date.now
    }
});

const User = module.exports = mongoose.model('Users', userSchema);
// Add User
module.exports.addUser = (user, callback) => {
    User.create(user, callback);
}

And Company Schema is (company.js) :

const mongoose = require('mongoose');

// Book Schema
const companySchema = mongoose.Schema({
    company_name:{
        type: String
    },
    target_address:{
        type: String
    },
    target_website:{
        type: String
    },
    created_on:{
        type: Date,
        default: Date.now
    },
    updated_on:{
        type: Date,
        default: Date.now
    }
});

const Company = module.exports = mongoose.model('Company', companySchema);

// Add Company
module.exports.addCompany = (comp, callback) => {
    Company.create(comp, callback);
}

Now My question is if I run Users.addUser function, and pass the above json to it, it should save/create user along with the company. and company ID should be saved in company property of user collection. if I do get users then it should return User data with company data fetched using that ID saved in the database

How to do that?

If I run the above files and try to insert data to it, It'll show the below error

 'Cast to Array failed for value "{ company_name: \'Moshi Moshi\', company_address: \'Bengaluru\' }" at path "company"',
        name: 'CastError',
        stringValue:
         '"{ company_name: \'Moshi Moshi\', company_address: \'Bengaluru\' }"',
        kind: 'Array',
        value: [Object],
        path: 'company',
        reason: [MongooseError] } },
  _message: 'Users validation failed',
  name: 'ValidationError' }
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
E:\MoshiMoshi\Projects\Maaamamia\blackhole-rest\models\users.js:17
        type: [{ type: ObjectId, ref: 'Company' }],
                       ^

ReferenceError: ObjectId is not defined

how to achive that functionality?

4

1 回答 1

2

first of all in your user schema company should not be an array because an user will have only single company Id according to your requirement.

 //incorrect
 company:{
    type: [{ type: Schema.Types.ObjectId, ref: 'Company' }],
    required: true
 },

 //correct
  company:{
     type: Schema.Types.ObjectId, 
     ref: 'Company',
     required: true
 },

And second while adding user you are passing entire company object to the company attribute. first you should add company and then store _id of saved company object into company attribute of user then save user object.

let yourJsonObject={
  username: "Lorem Ipsum",
  password: "Dolar Sit",
  company: {
     company_name: "Blah Blah",
     company_address: "Blah Blah Blah",
     company_website: "BlahBlah.com",
  }
}
      let companyObject=yourJsonObject.company;//your company object 
      let userObject= yourJsonObject //your user object

       let savedCompanyObject= //call add company method of your 
                                 //model with companyObject data
       userObject.company = savedCompanyObject._id;

      //now pass userObject to your addUser method of user model
于 2019-02-25T14:18:19.887 回答