2015-04-02 234 views
3

我想推到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


默认情况下,我的前端角应用正在发送标记为对象的数组。所以这是

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

什么是标签数组元素的数据类型? – chridam 2015-04-03 08:40:03

+0

默认情况下,它是一个对象数组,但我也尝试过一串字符串。对象就像这个'[{text:TAG_STRING_HERE},{...}]'。 – Noah 2015-04-03 16:21:08

回答

0

的解决方案如下。请注意,这是使用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) 
})