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