更新:
目前我有这个架构:
var Schema = new schema ({
name: String,
type: { type: String },
date: { type: Date },
descrip: String,
});
但是我使用这个模式来生成 2 个文档:
THE A TYPE ({
name: 'A',
type: 'TYPE_B',
date: { type: Date },
descrip: 'DESC_A',
});
THE B TYPE ({
name: 'B',
type: 'TYPE_B',
date: { type: Date },
descrip: 'DESC_B',
});
名称、类型和描述在 A 和 B 类型中始终相同,唯一改变的是日期字段,所以我在想,我该如何改进它?我如何在同一架构中插入多个日期,而不是始终创建具有相同名称、类型和描述值的文档?
所以我正在尝试在其他模式中创建一个模式,但我不知道这是否可能,是吗?
我是这样尝试的:
var mainSchema = new schema ({
name: String,
type: { type: String },
date: [ dateSchema ],
descrip: String,
});
var dateSchema = new Schema ({
date: {
type: Date
}
});
我想要的是创建两个 mainSchema,类型 a 和类型 b,并在其中插入日期...
我这样做对吗?我怎样才能实现我的目标?
我正在寻找具有良好解释的完整答案,这就是赏金的原因。我不接受 +/- 答案。
最佳答案
要创建包含多个日期的记录,您可以使用日期数组。
var mainSchema = new schema ({
name: String,
type: { type: String },
dates: [Date],
descrip: String,
});
文档如下
THE A TYPE ({
name: 'A',
type: 'TYPE_B',
dates: ["2014-01-22T14:56:59.301Z","2015-01-22T14:56:59.301Z"],
descrip: 'DESC_A',
});
THE B TYPE ({
name: 'B',
type: 'TYPE_B',
dates: ["2015-01-22T14:56:59.301Z","2014-01-22T14:56:59.301Z"],
descrip: 'DESC_B',
});
引用:http://mongoosejs.com/docs/schematypes.html
对于保存您可以使用的文档。
exports.save = function(req,res){
var test = new newSchema; // new object for newSchema domain.
test.name= req.body.name;
test.type= req.body.type;
test.desc= req.body.desc;
if(req.body.date){
req.body.forEach(function(date){ // For every element of date from client.
test.date.push(date) // This pushes each and every date given from the client into the date array.
})
}
test.save(function (saveErr, saved) { // Saves the new document into db.
if (saveErr) {
console.log(saveErr)
return;
}
res.status(HttpStatus.OK).json(saved);
});
};
对于更新,您可以使用 like。
exports.update = function(req,res){
newSchema.findOne({name: 'B'},function(err,test){ // Finds a record with name:'B' and stores in test the same can be done for name:'A'.
if(test){
if(req.body.date){
req.body.forEach(function(date){
test.date.push(date) // pushes dates into existing test document (update).
})
}
test.save(function (saveErr, saved) { // Saves (updates) the document.
if (saveErr) {
console.log(saveErr)
return;
}
res.status(HttpStatus.OK).json(saved);
});
}
});
};
希望这对您有所帮助。
关于javascript - 带有子文档的复杂架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27716398/