我定义了3个Schema:
var ChangeSetSchema = new Schema({
id: String,
...
workitems: [{ type: mongoose.Schema.Types.ObjectId, ref:'WorkItem' }]
});
var WorkItemSchema = new Schema({
id: String,
...
});
'ChangeSetSchema'中数组'workitems'中的id将与'WorkItemSchema'的'id'相同。 我想知道如何保存数据,例如Changeset架构:
router.route('/changeset')
.post(function(req, res) {
Changeset.find({ id: req.body.id }, function(err, changeset) {
if (err) {
res.send(err);
} else {
var changeset = new Changeset();
changeset.id = req.body.id;
changeset.url = req.body.url;
changeset.author = req.body.author;
changeset.createddate = req.body.createddate;
changeset.comment = req.body.comment;
//changeset.workitems = req.body.workitems;
changeset.save(function(err) {
if (!err) {
Changeset.find({})
.populate('workitems')
.exec(function(error, changesets) {
console.log(JSON.stringify(changesets, null, "\t"));
res.send('1');
})
}
});
}
});
})
每次保存'ChangeSet'时,是否必须创建并保存'WorkItems'对象?或者我可以告诉mongodb这两个是否已链接?
我在这里使用Express.js,完整代码:https://github.com/Trigu/ReleaseNotes/tree/master
答案 0 :(得分:0)
router.route('/changeset')
.post(function(req, res) {
Changeset.findOne({ id: req.body.id }, function(err, changeset) {
if (err) {
res.send(err);
} else {
//get Id before new
if(changeset){
var changesetWorkitemsId=changeset.workitems;
}
//creating new object here
var changeset = new Changeset();
changeset.id = req.body.id;
changeset.url = req.body.url;
changeset.author = req.body.author;
changeset.createddate = req.body.createddate;
changeset.comment = req.body.comment;
//set Id
if(changesetWorkitemsId){
changeset.workitems = changesetWorkitemsId;
}else{
changeset.workitems = req.body.workitems;
}
changeset.save(function(err) {
if (!err) {
Changeset.find({})
.populate('workitems')
.exec(function(error, changesets) {
console.log(JSON.stringify(changesets, null, "\t"));
res.send('1');
})
}
});
}
});
})