4

I'd like to push to an array that's within a subdocument in Mongoose/MongoDB.

Here is the schema:

var UsersSchema = new mongoose.Schema({
    user: String,
    stream: String,
    author: String,
    tags: Array,
    thumb: Number,
    added: Number
})

var ContentSchema = new mongoose.Schema( {
    title: String,
    url: String,
    description: String,
    text: String,
    users: [ UsersSchema ]  
})

I'd like to push an array into the UserSchema.tags array for a specific users sub-document.

I have tried this and several variations: https://stackoverflow.com/a/19901207/2183008


By default, my front-end Angular app is sending the tags as an array of objects. So it's

[ { 'text': TAG_STRING_HERE } ]

or

[ { 'text': TAG_STRING_HERE }, { 'text': TAG2_STRING_HERE } ]

But I've also tried just using and array of strings, which I'm fine doing if objects are a problem for some reason.


I have tried this:

var tags = req.body.tags,
    contentId = mongoose.Types.ObjectId( req.body.id )

Content.update( 
    { 'users._id': contentId },
    { $push: { 'users.tags': { $each: tags } } }
).exec()
.then( function ( result ) { 
    console.log( result )
    resolve( result )
}, function ( error ) {
    if ( error ) return reject( error )
})

Which gives me this error:

{ [MongoError: cannot use the part (users of users.tags) to traverse the element ({users: [ { user: "54f6688c55407c0300b883f2", added: 1428080209443.0, stream: "watch", _id: ObjectId('551ec65125927f36cf4c04e9'), tags: [] }, { user: "54f6688c55407c0300b883f2", added: 1428080222696.0, stream: "listen", _id: ObjectId('551ec65e25927f36cf4c04ea'), tags: [] } ]})]
name: 'MongoError',
code: 16837,
err: 'cannot use the part (users of users.tags) to traverse the element ({users: [ { user: "54f6688c55407c0300b883f2", added: 1428080209443.0, stream: "watch", _id: ObjectId(\'551ec65125927f36cf4c04e9\'), tags: [] }, { user: "54f6688c55407c0300b883f2", added: 1428080222696.0, stream: "listen", _id: ObjectId(\'551ec65e25927f36cf4c04ea\'), tags: [] } ]})' }
Community
  • 1
  • 1
Noah
  • 4,601
  • 9
  • 39
  • 52
  • What's the data type for any tag array element? – chridam Apr 03 '15 at 08:40
  • By default it is an array of objects, but I have also tried just an array of strings. The object is like this `[ { text: TAG_STRING_HERE }, { ... } ]`. – Noah Apr 03 '15 at 16:21

1 Answers1

0

The solution is below. Note this is using Q and Express. The part of note is the 'users.$.tags. I thought I had tried this but I guess not! I also used $pushAll instead, but $each might also work. My tags is always an array.

var tags = req.body.tags,
    contentId = mongoose.Types.ObjectId( req.body.id )

console.log( tags )

Content.update( 
    { 'users._id': contentId },
    { $pushAll: { 'users.$.tags': tags } }
).exec()
.then( function ( result ) { 
    console.log( result )
    resolve( result )
}, function ( error ) {
    if ( error ) return reject( error )
})
Noah
  • 4,601
  • 9
  • 39
  • 52