【问题标题】:Get last record from mongodb collection从 mongodb 集合中获取最后一条记录
【发布时间】:2018-11-23 07:54:13
【问题描述】:

我创建了一个 mongo 数据库,其中包含一个名为“rooms”的集合。
我想得到最后一个房间来创建下一个房间的 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]

我该怎么办?

【问题讨论】:

  • 我在后端做

标签: database mongodb collections record


【解决方案1】:

试试这个:var lastRoom = Room.find({}).sort(['id',1]).limit(1);

【讨论】:

  • Error: Invalid sort() argument, must be array of arrays
  • 试试这个:var lastRoom = Room.find({}).sort({'id':-1}).limit(1);
  • the last room was: [object Object] :/
  • 你能试着像这样控制它吗:console.log(lastRoom);您从控制台日志中看到了什么?
  • 一个奇怪的输出,似乎他没有找到。 (太长了,放在这里)
【解决方案2】:

查询后需要使用回调

Room.find({}).sort({ natural:-1 }).limit(1).then((data) => {
  console.log(data)
})

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 2011-01-12
  • 1970-01-01
  • 2011-05-24
相关资源
最近更新 更多