当我通过mongoose从mongo获取数据时...
const allAssets = await assets
.find({ company })
.sort([['createdAt', -1]])
.exec();
res.status(200).json({ assets: allAssets });
我总是得到_id和__v,但是我不想将它们发送到前端,有没有一种方法可以让我轻松地说出我不希望这些值或在发送它们之前将其删除?
{
"indistructable": true,
"_id": "5e345c2dc84be8995a5b4cf2",
"baseUri": "https://api.website.com/nameco8/",
"company": "jnameco8",
"description": "asset",
"image": "myimage.png",
"name": "jim",
"supply": 100,
"createdAt": "2020-01-31T16:56:13.816Z",
"updatedAt": "2020-01-31T16:56:13.816Z",
"__v": 0
},
我尝试添加
__v: {type: Number, select: false},
_id: { type: mongoose.Schema.Types.ObjectId, select: false },
到我的架构,但是当保存到架构时,我得到一个错误
"document must have an _id before saving"
答案 0 :(得分:2)
据我所知,模式是用于写的,以限制将未知字段写到文档中,从而使文档在整个集合中看起来相似,但是如果您需要删除读取中的几个字段,请尝试在.find()中进行投影:
"RedisServerException: ERR unknown command `MEMORY STATS`, with args beginning with:".
答案 1 :(得分:0)
Schema.find()
.select("-_id -__v")
.exec()
.then(result =>{
console.log(result);
})
除了@whoami - fakeFaceTrueSoul 的回答,你还可以在 find() 的 select 语句中添加多个 <" -fieldName ">