How to import one mongoose schema to another?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







3















I'm making a node app to consume json API and I'd like to separate parts of User schema into separate files because there are many fields in Profile and separating files keeps things cleaner:



So basically instead of



const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {
gender: {
type: String,
required: true
},
age: {
type: Number
},
//many more profile fields come here

}
});


I do this:



models/Profile.js is:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const profileSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
//the rest of profile fields
});

module.exports = Profile = mongoose.model('profile', profileSchema);


And the models/User.js is:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Profile = require('./Profile');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {type: Schema.Types.ObjectId, ref: 'Profile'},
});

module.exports = mongoose.model('users', userSchema);


The data for User and Profile are posted in the same json post.



However when node tries to save the object I get this error:



(node:4176) UnhandledPromiseRejectionWarning: ValidationError: users validation failed: profile: Cast to ObjectID failed for value "{ gender: 'male'...


How can I fix this?










share|improve this question

























  • Try : ref: 'Match._id'

    – Grégory NEUT
    Nov 22 '18 at 8:41













  • @GrégoryNEUT. Still I get the the same error. Please provide a complete answer.

    – Babr
    Nov 22 '18 at 8:45













  • The error is about Object Id. The Id you are passing for 'match' key is not object Id. You can use mongoose.Types.ObjectId(id); If it's different error then please share your create document code.

    – parth
    Nov 22 '18 at 9:46











  • @parth not sure what you mean. please elaborate with code.

    – Babr
    Nov 22 '18 at 9:51











  • match: {type: Schema.Types.ObjectId, ref: 'match'}. This match key requires object id. So if you're passing string then it will give you this error. Check regEx for this too. => value.match(/^[0-9a-fA-F]{24}$/)

    – parth
    Nov 22 '18 at 9:53


















3















I'm making a node app to consume json API and I'd like to separate parts of User schema into separate files because there are many fields in Profile and separating files keeps things cleaner:



So basically instead of



const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {
gender: {
type: String,
required: true
},
age: {
type: Number
},
//many more profile fields come here

}
});


I do this:



models/Profile.js is:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const profileSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
//the rest of profile fields
});

module.exports = Profile = mongoose.model('profile', profileSchema);


And the models/User.js is:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Profile = require('./Profile');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {type: Schema.Types.ObjectId, ref: 'Profile'},
});

module.exports = mongoose.model('users', userSchema);


The data for User and Profile are posted in the same json post.



However when node tries to save the object I get this error:



(node:4176) UnhandledPromiseRejectionWarning: ValidationError: users validation failed: profile: Cast to ObjectID failed for value "{ gender: 'male'...


How can I fix this?










share|improve this question

























  • Try : ref: 'Match._id'

    – Grégory NEUT
    Nov 22 '18 at 8:41













  • @GrégoryNEUT. Still I get the the same error. Please provide a complete answer.

    – Babr
    Nov 22 '18 at 8:45













  • The error is about Object Id. The Id you are passing for 'match' key is not object Id. You can use mongoose.Types.ObjectId(id); If it's different error then please share your create document code.

    – parth
    Nov 22 '18 at 9:46











  • @parth not sure what you mean. please elaborate with code.

    – Babr
    Nov 22 '18 at 9:51











  • match: {type: Schema.Types.ObjectId, ref: 'match'}. This match key requires object id. So if you're passing string then it will give you this error. Check regEx for this too. => value.match(/^[0-9a-fA-F]{24}$/)

    – parth
    Nov 22 '18 at 9:53














3












3








3








I'm making a node app to consume json API and I'd like to separate parts of User schema into separate files because there are many fields in Profile and separating files keeps things cleaner:



So basically instead of



const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {
gender: {
type: String,
required: true
},
age: {
type: Number
},
//many more profile fields come here

}
});


I do this:



models/Profile.js is:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const profileSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
//the rest of profile fields
});

module.exports = Profile = mongoose.model('profile', profileSchema);


And the models/User.js is:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Profile = require('./Profile');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {type: Schema.Types.ObjectId, ref: 'Profile'},
});

module.exports = mongoose.model('users', userSchema);


The data for User and Profile are posted in the same json post.



However when node tries to save the object I get this error:



(node:4176) UnhandledPromiseRejectionWarning: ValidationError: users validation failed: profile: Cast to ObjectID failed for value "{ gender: 'male'...


How can I fix this?










share|improve this question
















I'm making a node app to consume json API and I'd like to separate parts of User schema into separate files because there are many fields in Profile and separating files keeps things cleaner:



So basically instead of



const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {
gender: {
type: String,
required: true
},
age: {
type: Number
},
//many more profile fields come here

}
});


I do this:



models/Profile.js is:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const profileSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
//the rest of profile fields
});

module.exports = Profile = mongoose.model('profile', profileSchema);


And the models/User.js is:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Profile = require('./Profile');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {type: Schema.Types.ObjectId, ref: 'Profile'},
});

module.exports = mongoose.model('users', userSchema);


The data for User and Profile are posted in the same json post.



However when node tries to save the object I get this error:



(node:4176) UnhandledPromiseRejectionWarning: ValidationError: users validation failed: profile: Cast to ObjectID failed for value "{ gender: 'male'...


How can I fix this?







node.js mongoose






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 10:25







Babr

















asked Nov 22 '18 at 8:36









BabrBabr

320110




320110













  • Try : ref: 'Match._id'

    – Grégory NEUT
    Nov 22 '18 at 8:41













  • @GrégoryNEUT. Still I get the the same error. Please provide a complete answer.

    – Babr
    Nov 22 '18 at 8:45













  • The error is about Object Id. The Id you are passing for 'match' key is not object Id. You can use mongoose.Types.ObjectId(id); If it's different error then please share your create document code.

    – parth
    Nov 22 '18 at 9:46











  • @parth not sure what you mean. please elaborate with code.

    – Babr
    Nov 22 '18 at 9:51











  • match: {type: Schema.Types.ObjectId, ref: 'match'}. This match key requires object id. So if you're passing string then it will give you this error. Check regEx for this too. => value.match(/^[0-9a-fA-F]{24}$/)

    – parth
    Nov 22 '18 at 9:53



















  • Try : ref: 'Match._id'

    – Grégory NEUT
    Nov 22 '18 at 8:41













  • @GrégoryNEUT. Still I get the the same error. Please provide a complete answer.

    – Babr
    Nov 22 '18 at 8:45













  • The error is about Object Id. The Id you are passing for 'match' key is not object Id. You can use mongoose.Types.ObjectId(id); If it's different error then please share your create document code.

    – parth
    Nov 22 '18 at 9:46











  • @parth not sure what you mean. please elaborate with code.

    – Babr
    Nov 22 '18 at 9:51











  • match: {type: Schema.Types.ObjectId, ref: 'match'}. This match key requires object id. So if you're passing string then it will give you this error. Check regEx for this too. => value.match(/^[0-9a-fA-F]{24}$/)

    – parth
    Nov 22 '18 at 9:53

















Try : ref: 'Match._id'

– Grégory NEUT
Nov 22 '18 at 8:41







Try : ref: 'Match._id'

– Grégory NEUT
Nov 22 '18 at 8:41















@GrégoryNEUT. Still I get the the same error. Please provide a complete answer.

– Babr
Nov 22 '18 at 8:45







@GrégoryNEUT. Still I get the the same error. Please provide a complete answer.

– Babr
Nov 22 '18 at 8:45















The error is about Object Id. The Id you are passing for 'match' key is not object Id. You can use mongoose.Types.ObjectId(id); If it's different error then please share your create document code.

– parth
Nov 22 '18 at 9:46





The error is about Object Id. The Id you are passing for 'match' key is not object Id. You can use mongoose.Types.ObjectId(id); If it's different error then please share your create document code.

– parth
Nov 22 '18 at 9:46













@parth not sure what you mean. please elaborate with code.

– Babr
Nov 22 '18 at 9:51





@parth not sure what you mean. please elaborate with code.

– Babr
Nov 22 '18 at 9:51













match: {type: Schema.Types.ObjectId, ref: 'match'}. This match key requires object id. So if you're passing string then it will give you this error. Check regEx for this too. => value.match(/^[0-9a-fA-F]{24}$/)

– parth
Nov 22 '18 at 9:53





match: {type: Schema.Types.ObjectId, ref: 'match'}. This match key requires object id. So if you're passing string then it will give you this error. Check regEx for this too. => value.match(/^[0-9a-fA-F]{24}$/)

– parth
Nov 22 '18 at 9:53












3 Answers
3






active

oldest

votes


















0














You can define it like this:



/Match.js:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});

export const mongooseMatch = mongoose.model('match', matchSchema);


/User.js:



import mongooseMatch from './Match.js';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Match = require('./Match');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'Match'},
});

export const matchUser = userSchema.discriminator('matchUser', mongooseMatch);





share|improve this answer


























  • I guess your exports need some correction.

    – Babr
    Nov 22 '18 at 9:51



















0














If you create your model like



module.exports = Match = mongoose.model('match', matchSchema);


then you have to ref to it with same name as first argument, so instead of ref: 'Match' should be ref: match.



Then if you want to create new document you should do it like



const mongoose = require("mongoose");
const Match = require("./Match");
const User = require("./User");
...
const m = await Match.create({
gender: "male"
});

const u = await User.create({
username: 'user',
password: 'password',
match: m
});


And if you query it later e.g



console.log(await User.find({}).populate("match"));


you should get something like



[ { _id: 5bf672dafa31b730d59cf1b4,
username: 'user',
password: 'password',
match: { _id: 5bf672dafa31b730d59cf1b3, gender: 'Male', __v: 0 },
__v: 0 } ]


I hope that helped



...



Edit



If you getting all the data from one JSON you still have to somehow pass ObjectId as a parameter for your User model. And it has to be existing Match to make possible to populate query later.



E.g



const user = req.body; // user data passed
const match = user.match;
const savedMatch = await Match.create(match);
user.match = savedMatch;
const savedUser = await User.create(user);





share|improve this answer


























  • Well I'm working with a json API and the data for match and user come together in the same json post. So I cannot hardcode the match value as you did. Please adjust your answer to my specific scenario.

    – Babr
    Nov 22 '18 at 9:25













  • I adjusted, you can also quety your db instead of creating new match if that's your case

    – mhv
    Nov 22 '18 at 9:59











  • There should be a better way. match is parts of the user document so I can't see why I should save them separately.

    – Babr
    Nov 22 '18 at 9:59



















0














Match Model



// models/Match.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});
module.exports = Match = mongoose.model('match', matchSchema);


User Model



// models/User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'match'},
});

module.exports = User = mongoose.model('users', userSchema);


Then in your request add following code.



const User = require('../model/user');
const Match = require('../model/macth');

app.get('/test', (req, res) => {

let newMatch = new Match({ gender: 'male'});
newMatch.save().then(matchData => {
console.log(matchData);
let newUser = new User({ match: matchData._id, username: 'abc', password: '123456'});
newUser.save().then(userData => {
console.log(userData);
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));

});


Now Log out your result.






share|improve this answer
























  • match has no _id. match is part of user json

    – Babr
    Nov 22 '18 at 10:08











  • Please check the documentation for this. mongoosejs.com/docs/schematypes.html

    – parth
    Nov 22 '18 at 10:11











  • the docs does not answer my use case. Please have a look at my updated question. I tried to make it more explicit.

    – Babr
    Nov 22 '18 at 10:21













  • Use this Schema type. Schema.Types.Mixed. Ref stackoverflow.com/questions/43502870/…

    – parth
    Nov 22 '18 at 10:43












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53426809%2fhow-to-import-one-mongoose-schema-to-another%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You can define it like this:



/Match.js:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});

export const mongooseMatch = mongoose.model('match', matchSchema);


/User.js:



import mongooseMatch from './Match.js';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Match = require('./Match');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'Match'},
});

export const matchUser = userSchema.discriminator('matchUser', mongooseMatch);





share|improve this answer


























  • I guess your exports need some correction.

    – Babr
    Nov 22 '18 at 9:51
















0














You can define it like this:



/Match.js:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});

export const mongooseMatch = mongoose.model('match', matchSchema);


/User.js:



import mongooseMatch from './Match.js';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Match = require('./Match');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'Match'},
});

export const matchUser = userSchema.discriminator('matchUser', mongooseMatch);





share|improve this answer


























  • I guess your exports need some correction.

    – Babr
    Nov 22 '18 at 9:51














0












0








0







You can define it like this:



/Match.js:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});

export const mongooseMatch = mongoose.model('match', matchSchema);


/User.js:



import mongooseMatch from './Match.js';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Match = require('./Match');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'Match'},
});

export const matchUser = userSchema.discriminator('matchUser', mongooseMatch);





share|improve this answer















You can define it like this:



/Match.js:



const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});

export const mongooseMatch = mongoose.model('match', matchSchema);


/User.js:



import mongooseMatch from './Match.js';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Match = require('./Match');

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'Match'},
});

export const matchUser = userSchema.discriminator('matchUser', mongooseMatch);






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 22 '18 at 9:54

























answered Nov 22 '18 at 9:48









muellerramuellerra

111




111













  • I guess your exports need some correction.

    – Babr
    Nov 22 '18 at 9:51



















  • I guess your exports need some correction.

    – Babr
    Nov 22 '18 at 9:51

















I guess your exports need some correction.

– Babr
Nov 22 '18 at 9:51





I guess your exports need some correction.

– Babr
Nov 22 '18 at 9:51













0














If you create your model like



module.exports = Match = mongoose.model('match', matchSchema);


then you have to ref to it with same name as first argument, so instead of ref: 'Match' should be ref: match.



Then if you want to create new document you should do it like



const mongoose = require("mongoose");
const Match = require("./Match");
const User = require("./User");
...
const m = await Match.create({
gender: "male"
});

const u = await User.create({
username: 'user',
password: 'password',
match: m
});


And if you query it later e.g



console.log(await User.find({}).populate("match"));


you should get something like



[ { _id: 5bf672dafa31b730d59cf1b4,
username: 'user',
password: 'password',
match: { _id: 5bf672dafa31b730d59cf1b3, gender: 'Male', __v: 0 },
__v: 0 } ]


I hope that helped



...



Edit



If you getting all the data from one JSON you still have to somehow pass ObjectId as a parameter for your User model. And it has to be existing Match to make possible to populate query later.



E.g



const user = req.body; // user data passed
const match = user.match;
const savedMatch = await Match.create(match);
user.match = savedMatch;
const savedUser = await User.create(user);





share|improve this answer


























  • Well I'm working with a json API and the data for match and user come together in the same json post. So I cannot hardcode the match value as you did. Please adjust your answer to my specific scenario.

    – Babr
    Nov 22 '18 at 9:25













  • I adjusted, you can also quety your db instead of creating new match if that's your case

    – mhv
    Nov 22 '18 at 9:59











  • There should be a better way. match is parts of the user document so I can't see why I should save them separately.

    – Babr
    Nov 22 '18 at 9:59
















0














If you create your model like



module.exports = Match = mongoose.model('match', matchSchema);


then you have to ref to it with same name as first argument, so instead of ref: 'Match' should be ref: match.



Then if you want to create new document you should do it like



const mongoose = require("mongoose");
const Match = require("./Match");
const User = require("./User");
...
const m = await Match.create({
gender: "male"
});

const u = await User.create({
username: 'user',
password: 'password',
match: m
});


And if you query it later e.g



console.log(await User.find({}).populate("match"));


you should get something like



[ { _id: 5bf672dafa31b730d59cf1b4,
username: 'user',
password: 'password',
match: { _id: 5bf672dafa31b730d59cf1b3, gender: 'Male', __v: 0 },
__v: 0 } ]


I hope that helped



...



Edit



If you getting all the data from one JSON you still have to somehow pass ObjectId as a parameter for your User model. And it has to be existing Match to make possible to populate query later.



E.g



const user = req.body; // user data passed
const match = user.match;
const savedMatch = await Match.create(match);
user.match = savedMatch;
const savedUser = await User.create(user);





share|improve this answer


























  • Well I'm working with a json API and the data for match and user come together in the same json post. So I cannot hardcode the match value as you did. Please adjust your answer to my specific scenario.

    – Babr
    Nov 22 '18 at 9:25













  • I adjusted, you can also quety your db instead of creating new match if that's your case

    – mhv
    Nov 22 '18 at 9:59











  • There should be a better way. match is parts of the user document so I can't see why I should save them separately.

    – Babr
    Nov 22 '18 at 9:59














0












0








0







If you create your model like



module.exports = Match = mongoose.model('match', matchSchema);


then you have to ref to it with same name as first argument, so instead of ref: 'Match' should be ref: match.



Then if you want to create new document you should do it like



const mongoose = require("mongoose");
const Match = require("./Match");
const User = require("./User");
...
const m = await Match.create({
gender: "male"
});

const u = await User.create({
username: 'user',
password: 'password',
match: m
});


And if you query it later e.g



console.log(await User.find({}).populate("match"));


you should get something like



[ { _id: 5bf672dafa31b730d59cf1b4,
username: 'user',
password: 'password',
match: { _id: 5bf672dafa31b730d59cf1b3, gender: 'Male', __v: 0 },
__v: 0 } ]


I hope that helped



...



Edit



If you getting all the data from one JSON you still have to somehow pass ObjectId as a parameter for your User model. And it has to be existing Match to make possible to populate query later.



E.g



const user = req.body; // user data passed
const match = user.match;
const savedMatch = await Match.create(match);
user.match = savedMatch;
const savedUser = await User.create(user);





share|improve this answer















If you create your model like



module.exports = Match = mongoose.model('match', matchSchema);


then you have to ref to it with same name as first argument, so instead of ref: 'Match' should be ref: match.



Then if you want to create new document you should do it like



const mongoose = require("mongoose");
const Match = require("./Match");
const User = require("./User");
...
const m = await Match.create({
gender: "male"
});

const u = await User.create({
username: 'user',
password: 'password',
match: m
});


And if you query it later e.g



console.log(await User.find({}).populate("match"));


you should get something like



[ { _id: 5bf672dafa31b730d59cf1b4,
username: 'user',
password: 'password',
match: { _id: 5bf672dafa31b730d59cf1b3, gender: 'Male', __v: 0 },
__v: 0 } ]


I hope that helped



...



Edit



If you getting all the data from one JSON you still have to somehow pass ObjectId as a parameter for your User model. And it has to be existing Match to make possible to populate query later.



E.g



const user = req.body; // user data passed
const match = user.match;
const savedMatch = await Match.create(match);
user.match = savedMatch;
const savedUser = await User.create(user);






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 22 '18 at 9:57

























answered Nov 22 '18 at 9:17









mhvmhv

186




186













  • Well I'm working with a json API and the data for match and user come together in the same json post. So I cannot hardcode the match value as you did. Please adjust your answer to my specific scenario.

    – Babr
    Nov 22 '18 at 9:25













  • I adjusted, you can also quety your db instead of creating new match if that's your case

    – mhv
    Nov 22 '18 at 9:59











  • There should be a better way. match is parts of the user document so I can't see why I should save them separately.

    – Babr
    Nov 22 '18 at 9:59



















  • Well I'm working with a json API and the data for match and user come together in the same json post. So I cannot hardcode the match value as you did. Please adjust your answer to my specific scenario.

    – Babr
    Nov 22 '18 at 9:25













  • I adjusted, you can also quety your db instead of creating new match if that's your case

    – mhv
    Nov 22 '18 at 9:59











  • There should be a better way. match is parts of the user document so I can't see why I should save them separately.

    – Babr
    Nov 22 '18 at 9:59

















Well I'm working with a json API and the data for match and user come together in the same json post. So I cannot hardcode the match value as you did. Please adjust your answer to my specific scenario.

– Babr
Nov 22 '18 at 9:25







Well I'm working with a json API and the data for match and user come together in the same json post. So I cannot hardcode the match value as you did. Please adjust your answer to my specific scenario.

– Babr
Nov 22 '18 at 9:25















I adjusted, you can also quety your db instead of creating new match if that's your case

– mhv
Nov 22 '18 at 9:59





I adjusted, you can also quety your db instead of creating new match if that's your case

– mhv
Nov 22 '18 at 9:59













There should be a better way. match is parts of the user document so I can't see why I should save them separately.

– Babr
Nov 22 '18 at 9:59





There should be a better way. match is parts of the user document so I can't see why I should save them separately.

– Babr
Nov 22 '18 at 9:59











0














Match Model



// models/Match.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});
module.exports = Match = mongoose.model('match', matchSchema);


User Model



// models/User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'match'},
});

module.exports = User = mongoose.model('users', userSchema);


Then in your request add following code.



const User = require('../model/user');
const Match = require('../model/macth');

app.get('/test', (req, res) => {

let newMatch = new Match({ gender: 'male'});
newMatch.save().then(matchData => {
console.log(matchData);
let newUser = new User({ match: matchData._id, username: 'abc', password: '123456'});
newUser.save().then(userData => {
console.log(userData);
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));

});


Now Log out your result.






share|improve this answer
























  • match has no _id. match is part of user json

    – Babr
    Nov 22 '18 at 10:08











  • Please check the documentation for this. mongoosejs.com/docs/schematypes.html

    – parth
    Nov 22 '18 at 10:11











  • the docs does not answer my use case. Please have a look at my updated question. I tried to make it more explicit.

    – Babr
    Nov 22 '18 at 10:21













  • Use this Schema type. Schema.Types.Mixed. Ref stackoverflow.com/questions/43502870/…

    – parth
    Nov 22 '18 at 10:43
















0














Match Model



// models/Match.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});
module.exports = Match = mongoose.model('match', matchSchema);


User Model



// models/User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'match'},
});

module.exports = User = mongoose.model('users', userSchema);


Then in your request add following code.



const User = require('../model/user');
const Match = require('../model/macth');

app.get('/test', (req, res) => {

let newMatch = new Match({ gender: 'male'});
newMatch.save().then(matchData => {
console.log(matchData);
let newUser = new User({ match: matchData._id, username: 'abc', password: '123456'});
newUser.save().then(userData => {
console.log(userData);
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));

});


Now Log out your result.






share|improve this answer
























  • match has no _id. match is part of user json

    – Babr
    Nov 22 '18 at 10:08











  • Please check the documentation for this. mongoosejs.com/docs/schematypes.html

    – parth
    Nov 22 '18 at 10:11











  • the docs does not answer my use case. Please have a look at my updated question. I tried to make it more explicit.

    – Babr
    Nov 22 '18 at 10:21













  • Use this Schema type. Schema.Types.Mixed. Ref stackoverflow.com/questions/43502870/…

    – parth
    Nov 22 '18 at 10:43














0












0








0







Match Model



// models/Match.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});
module.exports = Match = mongoose.model('match', matchSchema);


User Model



// models/User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'match'},
});

module.exports = User = mongoose.model('users', userSchema);


Then in your request add following code.



const User = require('../model/user');
const Match = require('../model/macth');

app.get('/test', (req, res) => {

let newMatch = new Match({ gender: 'male'});
newMatch.save().then(matchData => {
console.log(matchData);
let newUser = new User({ match: matchData._id, username: 'abc', password: '123456'});
newUser.save().then(userData => {
console.log(userData);
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));

});


Now Log out your result.






share|improve this answer













Match Model



// models/Match.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});
module.exports = Match = mongoose.model('match', matchSchema);


User Model



// models/User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'match'},
});

module.exports = User = mongoose.model('users', userSchema);


Then in your request add following code.



const User = require('../model/user');
const Match = require('../model/macth');

app.get('/test', (req, res) => {

let newMatch = new Match({ gender: 'male'});
newMatch.save().then(matchData => {
console.log(matchData);
let newUser = new User({ match: matchData._id, username: 'abc', password: '123456'});
newUser.save().then(userData => {
console.log(userData);
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));

});


Now Log out your result.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 22 '18 at 10:05









parthparth

275317




275317













  • match has no _id. match is part of user json

    – Babr
    Nov 22 '18 at 10:08











  • Please check the documentation for this. mongoosejs.com/docs/schematypes.html

    – parth
    Nov 22 '18 at 10:11











  • the docs does not answer my use case. Please have a look at my updated question. I tried to make it more explicit.

    – Babr
    Nov 22 '18 at 10:21













  • Use this Schema type. Schema.Types.Mixed. Ref stackoverflow.com/questions/43502870/…

    – parth
    Nov 22 '18 at 10:43



















  • match has no _id. match is part of user json

    – Babr
    Nov 22 '18 at 10:08











  • Please check the documentation for this. mongoosejs.com/docs/schematypes.html

    – parth
    Nov 22 '18 at 10:11











  • the docs does not answer my use case. Please have a look at my updated question. I tried to make it more explicit.

    – Babr
    Nov 22 '18 at 10:21













  • Use this Schema type. Schema.Types.Mixed. Ref stackoverflow.com/questions/43502870/…

    – parth
    Nov 22 '18 at 10:43

















match has no _id. match is part of user json

– Babr
Nov 22 '18 at 10:08





match has no _id. match is part of user json

– Babr
Nov 22 '18 at 10:08













Please check the documentation for this. mongoosejs.com/docs/schematypes.html

– parth
Nov 22 '18 at 10:11





Please check the documentation for this. mongoosejs.com/docs/schematypes.html

– parth
Nov 22 '18 at 10:11













the docs does not answer my use case. Please have a look at my updated question. I tried to make it more explicit.

– Babr
Nov 22 '18 at 10:21







the docs does not answer my use case. Please have a look at my updated question. I tried to make it more explicit.

– Babr
Nov 22 '18 at 10:21















Use this Schema type. Schema.Types.Mixed. Ref stackoverflow.com/questions/43502870/…

– parth
Nov 22 '18 at 10:43





Use this Schema type. Schema.Types.Mixed. Ref stackoverflow.com/questions/43502870/…

– parth
Nov 22 '18 at 10:43


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53426809%2fhow-to-import-one-mongoose-schema-to-another%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents