4

Mongoose/MongoDB のサブドキュメント内にある配列にプッシュしたいと思います。

スキーマは次のとおりです。

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 ]  
})

UserSchema.tags特定のusersサブドキュメントの配列に配列をプッシュしたいと思います。

私はこれといくつかのバリエーションを試しました: https://stackoverflow.com/a/19901207/2183008


デフォルトでは、フロントエンドの Angular アプリはタグをオブジェクトの配列として送信しています。っていうことは

[ { 'text': TAG_STRING_HERE } ]

or

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

しかし、文字列の配列を使用してみました。これは、オブジェクトが何らかの理由で問題になっている場合でも問題ありません。


私はこれを試しました:

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 )
})

これは私にこのエラーを与えます:

{ [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: [] } ]})' }
4

1 に答える 1

0

解決策は以下です。これは Q と Express を使用していることに注意してください。注目の部分は'users.$.tags. 私はこれを試したと思ったが、そうではないと思う!私も$pushAll代わりに使用しました$eachが、うまくいくかもしれません。Mytagsは常に配列です。

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 )
})
于 2015-04-03T18:19:20.643 に答える