我对Node.js或Mongo经验不足,所以请原谅我在发布此文章时可能遇到的任何错误。
我有一个如下所示的模式:
var MessagesSchema = new mongoose.Schema({
title: {
type: String,
default: "Untitled Message Group"
},
members: {
type: Array
},
unreadCounts: {
type: Array
},
admins: {
type: Array
},
messages: {
sender: {
type: String
},
content: {
type: String
},
date: {
type: Number
}
}
});
来自用户的新消息被发送到“消息”部分,其信息被放入“发送者”,“内容”和“日期”数组中。我正在尝试使其一次只加载一定数量的消息,并且您可以单击“加载更多”按钮以加载更多消息。这是可行的,但是我的数组向后,旧消息首先加载,最新消息最后加载。所以,我试图做到这一点,以便在输入数据时反转数组。这是我用于$ pushing的旧方法:
Messages.updateOne({
'_id': ObjectId(data[2])
}, {
$push: {
messages: {
sender: data[1],
content: data[0],
date: Date.now()
}
},
$inc: {
"unreadCounts.$[]": 1
}
}, function (err, result) {
//...
});
这是我尝试过的新方法:
Messages.updateOne({
'_id': ObjectId(data[2])
}, {
$push: {
messages: {
$each: [{sender: data[1], content: data[0], date: Date.now()}],
$position: 0
}
},
$inc: {
"unreadCounts.$[]": 1
}
}, function (err, result) {
//...
});
这是其中一些数据的示例:
{
"_id": ObjectId("5ce4990a11fa8f0d6e27344a"),
//...
//Other stuff
//...
"messages": [{
"sender": "5c4ba709701212087e4d1bc9",
"content": "1st message sent",
"date": 1558485260497
}, {
"sender": "5c4ba709701212087e4d1bc9",
"content": "2nd message sent",
"date": 1558485261095
}, {
"sender": "5c4ba709701212087e4d1bc9",
"content": "3rd message sent",
"date": 1558485261446
}]
}
第3条消息是最后发送的消息。我希望顺序相反:第三个消息在顶部,然后是第二个消息,然后是第一个。
但是,由于某种原因,使用$ position似乎无效。项目会被推送到数组的末尾,而不是按预期的方式放在开头。
有人知道他们是否可以帮助我找出原因吗?也许我只是犯了一个愚蠢的错误?预先感谢!
答案 0 :(得分:1)
希望这会有所帮助:$push
型号:
var MessagesSchema = new mongoose.Schema({
title: {
type: String,
default: "Untitled Message Group"
},
members: {
type: Array
},
unreadCounts: {
type: Array
},
admins: {
type: Array
},
messages: [{
sender: {
type: String
},
content: {
type: String
},
date: {
type: Number
}
}]
});
现有数据:
{
"_id" : ObjectId("5ce4990a11fa8f0d6e27344a"),
"messages" : [
{
"sender" : "5c4ba709701212087e4d1bc9",
"content" : "1st message sent",
"date" : 1558485260497
},
{
"sender" : "5c4ba709701212087e4d1bc9",
"content" : "2nd message sent",
"date" : 1558485261095
},
{
"sender" : "5c4ba709701212087e4d1bc9",
"content" : "3rd message sent",
"date" : 1558485261446
}
]
}
查询:
db.messages.updateOne({
"_id": ObjectId("5ce4990a11fa8f0d6e27344a")
},{
$push: {
messages: {
$each: [{sender:"5c4ba709701212087e4d1bc9" , content: "4th message sent", date: Date.now()}],
$sort: {date: -1}
}
}
})
查询结果后:
{
"_id" : ObjectId("5ce4990a11fa8f0d6e27344a"),
"messages" : [
{
"sender" : "5c4ba709701212087e4d1bc9",
"content" : "4th message sent",
"date" : 1558575451749
},
{
"sender" : "5c4ba709701212087e4d1bc9",
"content" : "3rd message sent",
"date" : 1558485261446
},
{
"sender" : "5c4ba709701212087e4d1bc9",
"content" : "2nd message sent",
"date" : 1558485261095
},
{
"sender" : "5c4ba709701212087e4d1bc9",
"content" : "1st message sent",
"date" : 1558485260497
}
]
}