我创建了一个名为'rooms'的集合的mongo数据库 我想得到最后一个房间来创建下一个的id 你可以看到我恶心的代码:
会议室架构
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var Schema = mongoose.Schema;
var RoomSchema = mongoose.Schema({
name: {
type: String,
index: true
},
users: [{
type: Schema.Types.ObjectId,
ref: 'user'
}],
messages: {
type: [String]
},
subject: {
type: String
},
id: {
type: Number
}
});
var Room = module.exports = mongoose.model('Room', RoomSchema);
module.exports.createRoom = function (newRoom, callback) {
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(newRoom.password, salt, function (err, hash) {
newRoom.password = hash;
newRoom.save(callback);
});
});
}
试图获得最后一个房间
var lastRoom = Room.find({}).sort({$natural:-1}).limit(1);
然后我尝试运行它并输出'lastRoom',我得到了这个:
the last room was: [object Object]
我该怎么办?
答案 0 :(得分:0)
试试这个:var lastRoom = Room.find({})。sort(['id',1])。limit(1);
答案 1 :(得分:0)
您需要在查询后使用回调
Room.find({}).sort({ natural:-1 }).limit(1).then((data) => {
console.log(data)
})