我有一个名为notification的集合,我试图用findOne()
获取单个值 var allnotices = Notifications.findOne({eventownernumber:"2"},{sort: {noticedate: -1, limit: 1}}).noticemessage;
我希望得到eventownernumber
为2
的值,我想得到最新记录,我只想要一条记录。
即使noticemessage
是行字段的一部分,我也会收到noticemessage
未定义的错误。
这是架构
{
"_id": "tmkWCydSKZtYdrKTZ",
"eventoriginalid": "3bXvARk6K6yhee6Hi",
"lat": "-1.851881824302658",
"lng": "96.987469482421875",
"eventownernumber": "1",
"eventownernames": "Test 1",
"eventtitle": "ci",
"eventtime": "08:05",
"invited": "0",
"eventduration": "21",
"eventtype": "notification",
"eventcategory": "hackathon",
"eventstatus": "11",
"createdAt": {
"$date": "2016-11-02T12:38:40.378Z"
},
"noticedate": {
"$date": "2016-11-02T16:50:53.394Z"
},
"noticenumber": "2",
"noticenames": "Test 2",
"noticemessage": "Test 2 has joined your event ci",
"noticestatus": "12"
}
为什么noticemessage
未定义?。
答案 0 :(得分:0)
您需要将数字保存为eventownernnumber
的整数(并且请将其写为eventOwnerNumber
,这是可读性的良好做法),而不是字符串。使用input type="number"
或将值转换为整数,如下所示:
Number(valueHere);
您的查询的其余部分对我来说很好,但您不需要限制,因为您findOne()
并且找到了最新插入的文档noticedate: -1
另一件事是,您需要在insert()
:
noticeDate: new Date() //your current query should give you the right document after this change
答案 1 :(得分:0)
Collection.findOne(query).key
可能产生错误的基本可能性有四种:
undefined.key
.ready()
,即您需要等待才能访问它。常见的防御模式是:
const oneDoc = myCollection.findOne(query);
let myVar = oneDoc && oneDoc.key;
if ( myVar ) {
// do the thing
} else {
// handle the error
}