Mongoose schema.post(';find';)和schema.post(';findOne';)
app.jsMongoose schema.post(';find';)和schema.post(';findOne';),mongoose,mongoose-schema,Mongoose,Mongoose Schema,app.js Match.find({}).lean().exec(function(err, matches) {}); Match.findById(id).lean().exec(function(err, match) {}); 我在不同的路径中使用这两个查询 匹配型号: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var messageSchema = new Schema({ // .
Match.find({}).lean().exec(function(err, matches) {});
Match.findById(id).lean().exec(function(err, match) {});
我在不同的路径中使用这两个查询
匹配型号:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var messageSchema = new Schema({
// ...
message: {type: String, required: true},
}, {
timestamps: true
});
var matchSchema = new Schema({
// ...
messages: [messageSchema]
}, {
timestamps: true
});
matchSchema.post('find', function(result) {
result.forEach(function(chat) {
chat.messages.forEach(function(message) {
message.createdAt = new Date(message.createdAt).getTime();
message.updatedAt = new Date(message.updatedAt).getTime();
});
});
});
matchSchema.post('findOne', function(result) {
if (result !== null) {
result.messages.forEach(function(message) {
message.createdAt = new Date(message.createdAt).getTime();
message.updatedAt = new Date(message.updatedAt).getTime();
});
}
});
var Match = mongoose.model('Match', matchSchema);
module.exports = Match;
在Java中解析默认日期格式(如2016-05-19T13:29:07.731Z
)是一件痛苦的事(我在客户端使用),这就是为什么我用unix时间戳覆盖它,而unix时间戳在Java中很容易格式化。
这方面的问题是,find
和findOne
有重复的代码(message.createdAt
=…和message.updatedAt
)。
是否有一个钩子可以同时触发查询
find
和findByID
?所以我只需要写一次代码?因为find
不会触发findById
因为两个钩子看起来已经非常相似,所以可以将它们组合成一个函数,供所有(类似)钩子使用:
我相信
findOne
将触发findById
,因此这也应该包括在内。对于仍在搜索此函数的任何人,在每个数据库访问函数之后都会调用一个钩子
schema.post('init', function(doc) {
console.log('%s has been initialized from the db', doc._id);
});
这个钩子唯一的问题是它是同步的,不能处理承诺
此处记录:是的,可以。但是无论如何,对于所有不同的select(find/findOne/findById)类型,没有钩子吗?没有,似乎没有一个钩子可以捕获所有这些类型。
schema.post('init', function(doc) {
console.log('%s has been initialized from the db', doc._id);
});