javascript 如何在 mongoose 对象上添加临时属性仅用于响应,该属性未存储在数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22415758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:06:55  来源:igfitidea点击:

How do I add temporary properties on a mongoose object just for response, which is not stored in database

javascriptnode.jsmongoose

提问by bobmoff

I would like to fill a couple of extra temporary properties with additional data and send back to the response

我想用额外的数据填充几个额外的临时属性并发送回响应

'use strict';

var mongoose = require('mongoose');
var express = require('express');
var app = express();

var TournamentSchema = new mongoose.Schema({
    createdAt: { type: Date, default: Date.now },
    deadlineAt: { type: Date }
});

var Tournament = mongoose.model('Tournament', TournamentSchema);

app.get('/', function(req, res) {
    var tournament = new Tournament();

    // Adding properties like this 'on-the-fly' doesnt seem to work
    // How can I do this ?
    tournament['friends'] = ['Friend1, Friend2'];
    tournament.state = 'NOOB';
    tournament.score = 5;
    console.log(tournament);
    res.send(tournament);
});

var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});

But the properties wont get added on the Tournament object and therefor not in the response.

但是这些属性不会添加到 Tournament 对象上,因此不会添加到响应中。

回答by bobmoff

Found the answer here: Unable to add properties to js object

在这里找到答案:无法向 js 对象添加属性

I cant add properties on a Mongoose object, I have to convert it to plain JSON-object using the .toJSON()or .toObject()methods.

我无法在 Mongoose 对象上添加属性,我必须使用.toJSON()or.toObject()方法将其转换为普通的 JSON 对象。

EDIT:And like @Zlatko mentions, you can also finalize your queries using the .lean() method.

编辑:就像@Zlatko 提到的那样,您还可以使用 .lean() 方法完成查询。

mongooseModel.find().lean().exec()

... which also produces native js objects.

...这也产生了原生 js 对象。