javascript - 设置 Mongoose 文档的排序顺序

标签 javascript node.js mongodb mongoose

我有一个 Mongoose 模式:

models/profile.js

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var profileSchema = new mongoose.Schema({ 
    username: String,
    complete: { type: Boolean, default: false },
    email: { type: String, default: "" },
    city: { type: String, default: "" }
}, { discriminatorKey: 'accountType' });

profileSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('Profile', profileSchema);

这有两个与之相关的鉴别器:

models/finder.js

var Profile = require('./profile');

var Finder = Profile.discriminator('finder', new mongoose.Schema({
    position: { type: String, default: "" },
    skills: Array
}));

module.exports = mongoose.model("Finder");

models/helper.js

var Profile = require('./profile');

var Helper = Profile.discriminator('helper', new mongoose.Schema({
    jobTitle: { type: String, default: "" },
    lastPosition: { type: String, default: "" }
}));

module.exports = mongoose.model("Helper");

我在一个 express 框架中使用它,在一个页面上 - 如下所示 - 我想遍历 Profile 中的键/值对来构建一个表。

我想保留Schema中指定的顺序,让页面之间的表顺序保持一致。

是否可以在创建 Schema 时定义排序顺序?

这是我制作表格的 profile.ejs 文件:

<table class="table profile-display">
    <tbody>

    <% for(var key in profile.toObject({versionKey: false})) { %>
        <% if (key != '_id') { %>
            <% if (profile[key].length === 0){ %>
                <tr class="incomplete-warning table-rows">
            <% } else { %>
                <tr class="table-rows">
            <% } %>
                    <td class="key-text"><%=key.toUpperCase()%>:</td>
                    <td><%=profile[key]%></td>
                </tr>    
       <% } %>
    <% } %>

    </tbody>
</table>

如果我可以提供更多信息,请告诉我

最佳答案

您可以使用 retainKeyOrder

默认情况下,mongoose 会反转文档中的键顺序作为性能优化。例如,new Model({ first: 1, second: 2 }); 实际上会在 MongoDB 中存储为 { second: 2, first: 1 }。这种行为被认为已弃用,因为它有许多意想不到的副作用,包括难以操作 _id 字段为对象的文档。

Mongoose >= 4.6.4 为模式提供了一个 retainKeyOrder 选项,可确保 mongoose 始终保持对象键的正确顺序。

var testSchema = new Schema({ first: Number, second: Number }, { retainKeyOrder: true });
var Test = mongoose.model('Test', testSchema);
Test.create({ first: 1, second: 2 }); // Will be stored in mongodb as `{ first: 1, second: 2 }`

引用文献:

https://github.com/Automattic/mongoose/issues/1514 https://mongoosejs.com/docs/4.x/docs/guide.html#retainKeyOrder

关于javascript - 设置 Mongoose 文档的排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54872701/

相关文章:

java - 在 spring data mongodb 存储库的 @Query 注释中使用 $or 运算符

javascript - 我正在尝试创建一个 javascript 页面来将信息输入到表单中,但它不起作用

javascript - 是否可以添加自定义输入并使用 ScriptTag 调用第 3 方 API?

javascript - Promise 返回一个函数而不是一个对象

JavaScript:我可以访问包含导入模块的对象吗?

mysql - 如何在 bash 脚本中运行所有命令?

mysql - 书架关系未按预期工作

php - PHP 中来自 MongoDB 的 "Show Users"

javascript - 我遇到 'req.param.id' 问题

spring - 在将它们添加到 MongoDB 之前,如何在 Spring Data 中处理插入请求?