我有一个mongoose模式,它有一个包含项目的数组和另一个数组
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CompanySchema = new Schema({
dateCreated: { type: Date, default: Date.now },
ownerId: { type: String },
ceo: { type: String },
shareHolders: [{
userId: { type: String },
shares: { type: Number, default: 0 },
role: { type: String },
agreements: [{
agreementID: { type: String },
}]
}],
team: [{
userId: { type: String },
position: { type: String }
}],
});
module.exports = mongoose.model('Company', CompanySchema);
我尝试先检查一下shareholder数组中是否有一个包含userID特定值的项,然后我需要更新shareholder项并将一个新的agreementID推送到agreement数组中。我花了相当多的时间在Google上搜索和交换堆栈,但似乎无法实现这一点。
这是我到目前为止所拥有的,顺便说一句,这似乎总是创造一个新的股东,从来没有更新现有的股东。
更新股东我正在尝试这个
Company.update({
"_id": req.companyID,
"shareHolders.userId": req.userID
}, {
$push: {
"shareHolders.$.agreements.agreementID": req.agreementID
}
}, {
$set: {
"shareHolders.$.shares": ++req.shares
}
},
function(err) {
if (err) {
callback(err, err);
} else {
callback(null, 'success');
}
})
要查找股东是否存在,这总是导致股东不存在,并创建新股东
function checkShareHolder() {
console.log('checkShareHolder');
var date = moment().format('MM/DD/YYYY');
var data = {
companyID: agreement.applicant.applicantCompanyID,
userID: agreement.coSigner.coSignerID
}
company_worker.getCompanyByID(agreement.applicant.applicantCompanyID, function(err, result) {
if (err) {
console.log(err);
res.send(err);
} else {
company = result;
console.log('checkShareHolder');
process.nextTick(function() {
looper()
});
}
})
function looper() {
var updateShareholder = 'false';
var addShareHolder = 'false';
console.log('looper');
console.log(company.shareHolders);
if (company.shareHolders.length > 0) {
async.forEach(company.shareHolders, function(item, callback) {
console.log(item);
if (item.userID == agreement.coSigner.coSignerID) {
console.log('updateShareholder = true'),
updateShareholder = 'true',
callback()
} else(
console.log('addShareHolder = true'),
addShareHolder = 'true',
callback()
)
}, function(err) {
if (err) {
console.log(err);
}
if (addShareHolder == 'true') {
console.log('looper addShareHolder');
process.nextTick(function() {
addShareholder()
});
} else if (updateShareholder == 'true') {
console.log('looper updateShareholder');
process.nextTick(function() {
updateShareholder()
});
}
});
} else {
console.log('looper addShareHolder as nothing found');
process.nextTick(function() {
addShareholder()
});
}
}
};
1条答案
按热度按时间kcrjzv8t1#
您似乎应该使用{ $push:{“股东.$.协议”:{协议ID:req.agreementID} } }基于架构或将架构更改为协议:[{ type:String }]并使用{ $push:{“股东协议”:请求协议ID} } - Veeram
作品完美谢谢大家的帮助