【问题标题】:Push to array within subdocument in mongoose推送到猫鼬子文档中的数组
【发布时间】:2015-06-08 00:15:19
【问题描述】:

我想推送到 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: [] } ]})' }

【问题讨论】:

  • 任何标签数组元素的数据类型是什么?
  • 默认情况下它是一个对象数组,但我也尝试了一个字符串数组。对象是这样的[ { text: TAG_STRING_HERE }, { ... } ]

标签: arrays node.js mongodb mongoose subdocument


【解决方案1】:

解决方案如下。请注意,这是使用 Q 和 Express。注意的部分是'users.$.tags。我以为我已经尝试过了,但我想没有!我也改用了$pushAll,但$each 也可能有用。我的tags 始终是一个数组。

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

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 2016-06-05
    • 2018-05-17
    • 2020-07-10
    • 2020-03-17
    • 2019-10-13
    • 2015-06-26
    • 2016-01-29
    • 2019-03-22
    相关资源
    最近更新 更多