猫鼬不动findAndUpdateById [英] Mongoose unshift findAndUpdateById
本文介绍了猫鼬不动findAndUpdateById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是通过findByIdAndUpdate
将值 unshift
通过Mongoose文档数组的正确方法?
What's, if there is, the correct way to unshift
a value into a Mongoose document's array through findByIdAndUpdate
?
我尝试了此操作,但没有给出错误,但似乎也没有更新值
I tried this which doesn't give error but also doesn't seem to update the value
Schema.findById(id, function(err, doc){
console.log(doc.array.length); // => 1
Schema.findByIdAndUpdate(id,
{ array: { unshift: { property: 'value' } } },
{ upsert: true },
function(err, doc) {
console.log(doc.array.length); // Also => 1
}
);
});
$push
有效. $unshift
给出错误
[MongoError: exception: Unknown modifier: $unshift
文档说使用unshift
代替,但它不起作用.还是我使用错了?它不会给出任何错误,只是不会更新数组.
Docs say to use unshift
instead, but it doesn't work. Or am I using it wrong? It doesn't give any error, just doesn't update the array..
推荐答案
$position
运算符与$each
结合使用,与$push
可以实现相同的目的.
Found out that the $position
operator in conjunction with $each
works with $push
to achieve the same.
{ array: { $push: { property: {$each: ['value'], $position: 0 } } } },
这篇关于猫鼬不动findAndUpdateById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文