2 javascript mongoose mongodb node.js
更新:
目前我有这个架构:
var Schema = new schema ({
name: String,
type: { type: String },
date: { type: Date },
descrip: String,
});
Run Code Online (Sandbox Code Playgroud)
但我使用此架构生成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',
});
Run Code Online (Sandbox Code Playgroud)
A和B类型中的名称,类型和描述总是相同的,唯一改变的是日期字段,所以我在想,我该如何改进呢?如何在同一模式中插入多个日期,而不是始终创建具有相同名称,类型和描述值的文档?
所以我试图在其他架构中创建一个架构,但我不知道这是否可能,它是?
我是这样想的:
var mainSchema = new schema ({
name: String,
type: { type: String },
date: [ dateSchema ],
descrip: String,
});
var dateSchema = new Schema ({
date: {
type: Date
}
});
Run Code Online (Sandbox Code Playgroud)
我想要的是创建两个mainSchema,键入a并键入b,并在...中插入日期...
我这样做对吗?我怎样才能实现目标?
我正在寻找一个完整的答案和良好的解释,这就是赏金的原因.我不接受+/-答案.
要创建具有多个日期的记录,您可以使用日期数组.
var mainSchema = new schema ({
name: String,
type: { type: String },
dates: [Date],
descrip: String,
});
Run Code Online (Sandbox Code Playgroud)
文件如下
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',
});
Run Code Online (Sandbox Code Playgroud)
参考: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);
});
};
Run Code Online (Sandbox Code Playgroud)
对于更新,您可以使用喜欢.
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);
});
}
});
};
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
217 次 |
| 最近记录: |