如果使用猫鼬不是空的,如何有条件地返回字段
我有2个猫鼬模型,一种用于书籍,另一种用于作者。作者嵌入了书籍文档中
const mongoose = require("mongoose");
const BookSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
title: {
type: String,
minLength: 3,
maxlength: 80,
required: true
},
,并查询我正在这样做的书籍
async getBook(pid) {
let book = await Book.findOne({
_id: pid
})
.populate('user', 'name username')
;
if (!book) {
return false;
}
return book;
}
,如预期的返回名称和作者的用户名。
但是,我想做的是如果用户名是空的,则返回名称,或者仅在用户名不为空时返回用户名。我该怎么做?
I have 2 mongoose models, one for books and one for authors. The author is embedded in the book document
const mongoose = require("mongoose");
const BookSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
title: {
type: String,
minLength: 3,
maxlength: 80,
required: true
},
and to query the books I am doing this
async getBook(pid) {
let book = await Book.findOne({
_id: pid
})
.populate('user', 'name username')
;
if (!book) {
return false;
}
return book;
}
This works as expected returning name and username of the author.
However, what I would like to do is to return the name if username is empty, or only return the username if username is not empty. How can I do that please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$ ifnull
可以实现所需的行为。这是 mongo playground 供您参考。
The desired behaviour is achievable through
$ifNull
when wrangling the lookup subpipeline.Here is the Mongo playground for your reference.