所以我有一个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);
我试图首先检查股票阵列中是否有一个包含userID特定值的项目,然后我需要更新股东项目并将新的agreementID推送到协议数组中。我花了几个小时谷歌搜索和堆栈交换,但似乎无法实现这一点。
这就是我到目前为止所看到的这个似乎总是创建一个新的股东永远不会更新现有股东。
更新股东我正在尝试这个
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()
});
}
}
};
答案 0 :(得分:0)
看起来你应该根据模式使用{$ push:{“shareHolders。$。agreement”:{agreementID:req.agreementID}}}或者将你的模式更改为协议:[{type:String}]和使用{$ push:{“shareHolders。$。agreement”:req.agreementID}} - Veeram
非常感谢大家的帮助