I have a mongoose schema that looks like this, that I am able to update and query just fine:
// Subscriber Schema
var Subscriber = new Schema({
'user': ObjectId,
'level': { type: String, enum: [ 'sub', 'poster', 'blocked' ] }, //blocked means users has opted out of list
'dateAdded': { type: Date, default: Date.now }
});
// Group Schema
var Group = new Schema({
'groupEmail': { type: String, lowercase: true, validate: [validatePresenceOf, 'an email is required'], index: { unique: true } },
'groupOwner': ObjectId,
'groupName': String,
'twitterFeed': String,
'subscribers': [Subscriber],
'createdAt': { type: Date, default: Date.now }
});
I'm trying to update a Subscriber within the Group document, and change its level, then save the change. I'm able to find the group just fine using:
Group.findOne({ _id: req.params.groupId }, function(err, g)
Once I have the group, I want to find a subscriber so I can update it. If I try:
g.subscribers.update({ 'user': req.params.userId }, { level: newStatus });
I get:
TypeError: Object { user: 4fc53a71163006ed0f000002,
level: 'sub',
_id: 4fd8fa225904a5451c000006,
dateAdded: Wed, 13 Jun 2012 20:37:54 GMT },{ user: 4fda25ac00cd9bdc4f000004,
level: 'sub',
_id: 4fda270bbce9f8d058000005,
dateAdded: Thu, 14 Jun 2012 18:01:47 GMT },{ user: 4fda2a634499dfd16e00000d,
level: 'sub',
_id: 4fda2a634499dfd16e00000e,
dateAdded: Thu, 14 Jun 2012 18:16:03 GMT } has no method 'update'
I've tried various permutations of update, find, etc. but always get the "has no method" error. What am I doing wrong? Is there a different way I should be updating Subscriber.level?
Thanks!!
@eltoro is mostly correct, arrays do not have an update
method, and the suggestion to use Group.update
is a good one, but the update syntax is missing the $
in subscribers.$.level
.
Group.update(
{_id: req.params.groupId, 'subscribers.user': req.params.userId},
{ 'subscribers.$.level': newStatus }, function(err, result) {}
);
I think you're getting the error because you're calling update on the instance instead of the model.
Maybe try something like this:
Group.update(
{_id: req.params.groupId, subscribers.user: req.params.userId},
{ subscribers.level: newStatus }, function(err, result) {}
);