使用MongoDB字段值作为变量
问题描述:
我想从Mongo记录中获取字段并将其值存储在变量中。下面的查询返回正确的记录,但它也返回整个对象。我如何取得'sid'字段的价值?使用MongoDB字段值作为变量
这里是我的架构:
var SessionsSchema = mongoose.Schema({
session: {
sid: String,
dataloop: {
timeStamp: Date,
sensorValues:{
value: Number,
index: Number
}
}
}
});
下面是该查询&功能我使用的存储值:
Sessions.find().sort({ 'sid' : -1 }).limit(1).exec(function(err, post) {
if(post == null){
lastSession = post.sid;
sessionID = 1;
}else {
lastSession = post.sid;
sessionID = lastSession++;
}
});
答
find
返回一个数组,而不是一个对象,你需要作为数组访问post
。使用post[0]
代替post
另外,post[0].sid
将被定义,您需要使用它作为post[0].session.sid
。
Sessions.find().sort({ 'sid' : -1 }).limit(1).exec(function(err, post) {
if(post.length===0){
lastSession = post[0].session.sid;
sessionID = 1;
}else {
lastSession = post[0].session.sid;
sessionID = lastSession++;
}
});
该查询只返回集合中的第一条记录,它应该检查整个集合中的SID字段,然后返回最高值。 – HjalmarCarlson
这是行不通的。我需要在嵌入式文档中指定字段位置。 – HjalmarCarlson