我有以下文档结构,需要使用mongoose添加到子子文档:
var organization = module.exports = mongoose.Schema({
teams: [{
permissions: [{ permission: String }]
}]
})
organization.methods.addTeam = function(team){
//the save occurs in a repository layer later on, for now I am just prepping the object for the save
this.teams.push(team);
var subdoc = this.teams[0];
subdoc.isNew;
}
//Ideally, something like this would be great but I have not been able to find any doc that really provides a good example on this scenario
organization.methods.addPermission = function(id(team), permission){
var teams = this.teams.id(id)
teams.permissions.push(permission);
var subsubdoc = teams.permission[0];
subsubdoc.isNew;
}
我是node.js和mongodb的新手,并且遇到了子子文档的以下问题。在以下示例中,我需要添加权限数组。我在组织架构上添加了一个新方法,以便根据我找到的示例处理将团队添加到组织中。我想在组织架构中添加一个类似的方法来处理向团队子文档添加权限。我还想检查并确保在添加之前该权限尚不存在。我该如何处理这种情况?
答案 0 :(得分:0)
看看MongoDB的$addToSet运营商。
// file: modules/organization/add_permission.js
var Organization = mongoose.model('Organization');
exports.addPermission = function(teamId, permission) {
Organization.update(
{_id: teamId}, // query
{$addToSet: {permissions: {permission: permission}}}, // update
function(err) { // callback
// handle error
// other logic
}
);
};
或者在Organization
猫鼬模型上执行与方法类似的操作。