我有一个 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/