【发布时间】:2016-02-03 01:47:05
【问题描述】:
我有两个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 对象时,没有为保存的Contact 分配_id。
但是当我使用这个架构时:
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'
}]
}
我错过了什么?
【问题讨论】:
-
您能否请添加您如何生成和保存我认为错误存在的对象。
-
@Sprotte 当然,我已经编辑了这个问题。谢谢!
-
如何创建
Client模型? -
@kba 没什么特别的:
mongoose.model('Client', ClientSchema);
标签: javascript node.js mongoose mongoose-schema