2015-04-02 101 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) 
})