2016-08-13 66 views
1

我正在嘗試爲我的學校項目構建一個消息傳遞系統。我創建MongoDB中的模式,看起來像這樣:使用mongodb,node和express存儲數組中的對象

var userSchema = new mongoose.Schema({ 
    firstName: String, 
    lastName: String, 
    messages: [] 
}); 

我想存儲在消息的對象,看起來類似於這樣:我希望能夠存儲

{ 
from: 'fromUsername', 
to: 'toUsername', 
time: new Date(), 
msg: 'message is here' 
} 

在消息數組下的模式中。有沒有辦法將它推到shcema?不知道如何處理這個任務。謝謝!

回答

0

您可以使用th $push運算符將您的對象值附加到消息數組中。

如何使用$推你userSchema

// How to update a user already created 
var User = mongoose.model('User'); 

User.update(
    { _id: id }, 
    { $push: {messages : { 
     from: 'fromUsername', 
     to: 'toUsername', 
     time: new Date(), 
     msg: 'message is here'}} 
    }) 
+0

請問您能否澄清此代碼的放置位置?我不確定如何使用這段特定的代碼,或者如何從角度前端調用此代碼。非常感謝您的幫助! –

+0

您需要將這部分代碼放入nodejs服務器的路由中(讓服務器向db而不是客戶端發出請求)。在角度前端中,使用正文中的消息對象向服務器發出$ http POST請求。 – NotBad4U

0

你可以嵌入作爲用戶文檔的一部分的消息模式分別定義模式(如消息數組中的項目)的一個例子:

var messageSchema = new mongoose.Schema({ 
    from: String, 
    to: String, 
    time: { type: Date, default: Date.now }, 
    msg: String 
}) 

var userSchema = new mongoose.Schema({ 
    firstName: String, 
    lastName: String, 
    messages: [messageSchema] 
}); 

mongoose.model('User', userSchema); 

給定的信息添加到消息數組,遵循的模式:

// retrieve user model 
var User = mongoose.model('User'); 

// create user instance 
var user = new User({ 
    firstName: 'Alice', 
    lastName: 'Bob' 
}); 

// create a message 
user.messages.push({ 
    from: 'fromUsername', 
    to: 'toUsername', 
    msg: 'message is here' 
}); 

您可以選擇排除時間字段,因爲當您保留模型時,您將定義其默認值。

user.save(function (err, user) { 
    if (!err) console.log(JSON.stringify(user, null, 4)); 
}); 
+0

嘿,那裏,謝謝你的回覆!我對平均堆棧很陌生。我在查看服務器內如何處理時遇到問題。用戶和用戶都會將他們的消息添加到他們的消息數組中嗎?因此,如果用戶a發送給用戶b,那麼用戶a和用戶b都會在「messages:[messageSchema]」中輸入消息嗎?謝謝! –

相關問題