私は2つのSchemaオブジェクトを持っています:
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'}});
残念ながら、Clientオブジェクトを保存すると、保存された _id に割り当てられませんContact。
しかし、このスキーマを使用すると:
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'}});
連絡先は、自動生成された _id で保存されます。
クライアントを保存する方法は非常に簡単です。
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);
});
req.body の内容は次のとおりです。
{
name: 'A name for the client',
contacts: [ {
name: 'A name for the contact',
email: 'noy@test.com',
role: 'UFO'
}]
}
私は何が欠けていますか?