从 findOneAndUpdate 更改响应文档对象
Changing response doc object from findOneAndUpdate
假设我得到了这么一小段代码:
Room.findOneAndUpdate({ Roomid: roomid }, { $push: { UsersMeta: UserMeta}}, { new: false }, function (err, room) {
if (err) console.log(err);
console.log('room output:');
console.log(room);
client.emit('others', room);
})
它正在数据库中搜索一个文档,更新它,然后将这个 room
文档以更新前的状态发送回客户端。我需要对响应的 room
进行一些更改,特别是删除那些 _id、__v,并且可能还有文档的任何其他自定义部分。
我想做什么:
在创建架构时使用 toObject.transform
var RoomSchema = mongoose.Schema({
Roomid: { type: String, unique: true },
///stuff///
});
RoomSchema.options.toObject.transform = function (doc, ret, options) {
// remove the _id of every document before returning the result
delete ret._id;
}
失败:收到 cannot set property 'transform' of undefined
错误。
将提到的代码块更改为:
Room.find({ Roomid: roomid })
.update({ $push: { UsersMeta: UserMeta} })
.select({ _id: 0 })
.exec(function (err, room) {
if (err) console.log(err);
console.log('room output:');
console.log(room);
client.emit('others', room);
})
失败:总是在 room
输出中收到 []。
现在我停止在 Schema 声明中手动设置 {_id: false}
,首先完全摆脱了 _id
。因为我想为房间使用自定义随机 ID,所以我似乎不需要那些 _id
。但我不确定,这样的处理会不会造成一些不愉快的后果。
而且,此外,可能需要保留一些非 _id
文档属性的问题对我来说是一个未解之谜。
谢谢关注
您可以执行以下操作,它应该有效;
RoomSchema.set('toJSON', {
transform: function (doc, ret, options) {
delete ret._id;
delete ret.__v;
}
});
假设我得到了这么一小段代码:
Room.findOneAndUpdate({ Roomid: roomid }, { $push: { UsersMeta: UserMeta}}, { new: false }, function (err, room) {
if (err) console.log(err);
console.log('room output:');
console.log(room);
client.emit('others', room);
})
它正在数据库中搜索一个文档,更新它,然后将这个 room
文档以更新前的状态发送回客户端。我需要对响应的 room
进行一些更改,特别是删除那些 _id、__v,并且可能还有文档的任何其他自定义部分。
我想做什么:
在创建架构时使用 toObject.transform
var RoomSchema = mongoose.Schema({
Roomid: { type: String, unique: true },
///stuff///
});
RoomSchema.options.toObject.transform = function (doc, ret, options) {
// remove the _id of every document before returning the result
delete ret._id;
}
失败:收到 cannot set property 'transform' of undefined
错误。
将提到的代码块更改为:
Room.find({ Roomid: roomid })
.update({ $push: { UsersMeta: UserMeta} })
.select({ _id: 0 })
.exec(function (err, room) {
if (err) console.log(err);
console.log('room output:');
console.log(room);
client.emit('others', room);
})
失败:总是在 room
输出中收到 []。
现在我停止在 Schema 声明中手动设置 {_id: false}
,首先完全摆脱了 _id
。因为我想为房间使用自定义随机 ID,所以我似乎不需要那些 _id
。但我不确定,这样的处理会不会造成一些不愉快的后果。
而且,此外,可能需要保留一些非 _id
文档属性的问题对我来说是一个未解之谜。
谢谢关注
您可以执行以下操作,它应该有效;
RoomSchema.set('toJSON', {
transform: function (doc, ret, options) {
delete ret._id;
delete ret.__v;
}
});