【问题标题】:Updating an array using conditionals with mongoose in node.js在 node.js 中使用带有猫鼬的条件更新数组
【发布时间】:2016-01-27 02:24:48
【问题描述】:

我正在尝试更新为使用 Mongoose 创建了架构的 MongoDB 集合。我的目标是删除一个称为“警报”的数组中小于(过去)当前时间的所有元素。

这是我的 Mongoose 架构:

var mongoose = require('mongoose');

var ReminderSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    phone: Number,
    email: String,
    medication: String,
    alarms: [Date]
});

module.exports = mongoose.model('Reminder', ReminderSchema); 

这里是更新。我正在尝试删除所有小于当前日期的警报。

var date = new Date();
var Reminder = require('./models/Reminders.js');

//remove ALL alarms that are are before current time
Reminder.update({alarms: {$lte: date}}, {$pullAll: {alarms: {$lte: date}}}, function(err, updated){
    if(err){
         console.log(err);
     }
     else {
         console.log(updated);
     }
 });

我目前收到此错误:

{ [MongoError: $pullAll requires an array argument but was given a Object]
name: 'MongoError',
message: '$pullAll requires an array argument but was given a Object',
driver: true,
index: 0,
code: 2,
errmsg: '$pullAll requires an array argument but was given a Object' }

有什么想法吗?

【问题讨论】:

  • 只需将 $pullAll 替换为 $pull
  • 这行得通。谢谢。

标签: javascript node.js mongodb mongoose


【解决方案1】:

$pullAll 接收一个数组而不是一个对象:

{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } }

$pullAll 运算符删除指定值的所有实例 从现有数组。与删除的 $pull 运算符不同 通过指定查询元素,$pullAll 删除匹配的元素 列出的值。

你应该使用的解决方案 $pull

Reminder.update({alarms: {$lte: date}},{$pull:{alarms: { $lte : new Date()}}}, 
 function(err, updated){
if(err){
     console.log(err);
 }
 else {
     console.log(updated);
 }
});

https://docs.mongodb.org/manual/reference/operator/update/pullAll/

【讨论】:

  • 这样就完成了。非常感谢。
猜你喜欢
  • 2017-05-10
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
相关资源
最近更新 更多