【发布时间】:2017-04-04 00:44:10
【问题描述】:
这是要查看的主要代码
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);
}
);}
(我将代码修改为通用代码。如果您需要具体代码,请让我更新此帖子)
我正在尝试使用 upsert: true 执行 Model.findOneandUpdate。
我的代码在特定事件发出时执行
feedparser.on('readable', function() {
update(this.read());
});
由于 'array.index': {$ne: value.index} 查询,代码在第一次执行后创建一个新的。
因此,
db.collection.find()
返回具有相同属性但 ObjectId 不同的多个文档。
例如,
{"_id":ObjectId("1"), test: "A", array:[{index:"1"}]}
{"_id":ObjectId("2"), test: "A", array:[{index:"1"}]}
我想做代号
- 检查文档是否存在。
- 如果存在,则将新值添加到文档的数组中。此外,index 的新值应该是唯一的。
- 如果不存在,则创建新文档并将新值添加到新文档的数组中。
更新:
我也尝试通过
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);
});
}
这段代码导致什么都不做。
更新
我也试试这个
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);
});
}
});
但是,它通过每个不同的索引值创建新的文档。
更新
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();
}
});
它也不起作用......
【问题讨论】:
标签: javascript node.js mongodb mongoose