I have two Schema
objects:
contact.js:
/**
* Contact Schema
*/
var ContactSchema = new Schema({
name: String,
role: String,
phone: String,
email: String,
primary: Boolean
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}, _id: true, id: true});
client.js:
/**
* Client Schema
*/
var ClientSchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
comments: {
type: String,
trim: true
},
creator: {
type: Schema.ObjectId,
ref: 'User'
},
contacts: [ContactSchema],
address: String,
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}});
Alas, when I save the Client
object, no _id is assigned to the saved Contact
.
But when I use this schema:
client.js:
/**
* Client Schema
*/
var ClientSchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
comments: {
type: String,
trim: true
},
creator: {
type: Schema.ObjectId,
ref: 'User'
},
contacts: [{
name: String,
role: String,
phone: String,
email: String,
primary: Boolean
}],
address: String,
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}});
Contacts are saved with an auto-generated _id.
The way I save the clients is very straight forward:
var client = new Client(req.body);
client.creator = req.user;
client.save(function (err) {
if (err) {
console.log(err);
return res.status(500).json({
error: 'Cannot save the client'
});
}
res.json(client);
});
And the contents of req.body is:
{
name: 'A name for the client',
contacts: [ {
name: 'A name for the contact',
email: 'noy@test.com',
role: 'UFO'
}]
}
What am I missing?
So, I was completely off here. My problem was the way I was requiring the schema. I was using:
var ContactSchema = require('./contact');
to get the schema, but I didn't add module.exports = ContactSchema;
at the end of the contact.js file.
Thanks to this question: MongoDB: How to use one schema as sub-document for different collections defined in different files I was able to solve mine (world's weirdest behavior though, since everything else was working).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.