0
這裏是主代碼尋找到如何正確使用貓鼬查詢,查找和更新對象數組
function update(feed){
//.. do set up
var target = feed.title;
var value = {index: feed.value};
var query = { test: target, 'array.index': {$ne: value.index} },
update = { $push : {"array" : value} },
options = { upsert: true, new: true };
Model.findOneAndUpdate(query, update, options, function(err, docs) {
if(err) throw err;
console.log(docs);
}
);}
(我修改了代碼是一般。如果你需要特定的代碼,只是問我更新這個後)
我試圖做Model.findOneandUpdate與UPSERT:真。
我的代碼執行時具體的事件發出
feedparser.on('readable', function() {
update(this.read());
});
的Becasue 'array.index':{$ NE:value.index}查詢,代碼生成了第一次執行後新的。
因此,
db.collection.find()
返回具有不同的ObjectId相同屬性的多個文檔。
例如,
{ 「_id」:的ObjectId( 「1」),測試: 「A」,陣列:[{指數: 「1」}]}
{ 「_id」:的ObjectId( 「2」),測試: 「A」,陣列:[{指數: 「1」}]}
我想成爲代碼做
- 檢查文件存在與否。
- 如果存在,則向Document的數組添加新值。此外,新值應由索引唯一。
- 如果不存在,則創建新文檔並向新文檔的數組添加新值。
UPDATE:
我也試圖通過
var doc = Model.findOne({ test: target });
if(doc != null){
var query = { _id: doc._id, 'array.index': {$ne: value.index} };
var update = { $push : {"array" : value} };
var options = {new: true};
Model.update(query, update, options, function(err, d){
if(err) throw err;
console.log(d);
});
}else{
doc = {
test: target,
array:[value]
};
Model.create(doc, function (err, res){
if(err) throw err;
console.log(res);
});
}
在無可奈何做此代碼的結果。
UPDATE
我也
Model.findOne({ test:target }, function(err, doc){
if(doc === null){
doc = {
test: target
arrays:[value]
};
Animation.create(doc, {new: true}, function (err, res){
if(err) throw err;
console.log(res);
});
}else{
var query = { _id: doc._id, 'arrays.index': {$ne: value.index} };
var update = { $push : {"arrays" : value} };
var options = {new: true};
Animation.update(query, update, options, function(err, res){
if(err) throw err;
console.log(res);
});
}
});
嘗試這個但是,它通過每個不同的索引值來創建新的文檔。
UPDATE
var query = { test: target, 'array:index': {$ne: value.index} };
var update = { $push : {'array' : value}};
var options = {new: true};
Model.findOneAndUpdate(query, update, options, function(err, doc){
if(err) throw err;
if(doc === null){
doc = new Model({
test: target,
array:[value]
});
doc.save();
}
});
它也沒有工作...