[英]How can i use an if statement in a mongoose query?
我有一個名為Feed的mongodb集合,它具有一個名為“ type”的屬性。 根據該字符串,我想發送一個帶有json的可變字段。 例如,如果類型是“照片”,我想這樣做
schema.find({number: "123456"},"body number",
function(err, data) {
但是如果字符串是故事,而不是照片; 在相同的“ schema.find”查詢中,應使用“ body url”而不是“ body number”創建一個json。 它們都應使用相同的json傳遞。
res.json(data);
舉一個清晰的例子,我希望我的json是這樣的。 在您設置時,字段會根據“類型”而變化。 但實際上它們都在同一個集合中。
[
{
type: 'photo',
number: 123456,
url: 'asd.jpg',
},
{
type: 'story',
body: 'hello',
number: 123456,
}
]
因此,基本上,您想從Feed集合中返回某些文檔字段,這些字段在變量中指定,例如"firstName pic points photos"
。
有story
字段的Feed文檔嗎?
Model.find()不會創建任何架構。
也許用進一步的代碼進行編輯,以便我們理解該命令。
對於像這樣的特定於文檔的JSON格式,您可以覆蓋Feed
模型的默認toJSON
方法,如本要點所示。
更新
如果您希望在文檔中具有這種靈活性,那么它會更加容易。 只需定義您的架構以包括所有可能的字段,然后僅將適用於給定文檔的字段設置為其type
。 您不使用的字段不會出現在文檔中(或JSON響應中)。 因此,您的架構如下所示:
var feedSchema = new Schema({
type: { type: 'String' },
venue: Number,
url: String,
body: String
});
看一下mongoose-schema-extend 。 使用“區分鍵”功能,您可以指示.find()在每種情況下創建正確的模型。
您的代碼應如下所示(未經測試):
var feedSchema = new Schema({
venue: Number,
}, {discriminatorKey : 'type' }});
var photoSchema = feedSchema.extend({
url: String
});
var storySchema = feedSchema.extend({
body: String
});
var Feed= mongoose.model('feed', feedSchema );
var Photo= mongoose.model('photo', photoSchema );
var Story= mongoose.model('story', storySchema );
//'photo' and 'story' will be the values for 'type' key
Feed.find({venue: "123456"}, function(err, models) {
console.log(models[0] instanceof Photo); // true
console.log(models[0] instanceof Story); // false
console.log(models[1] instanceof Photo); // false
console.log(models[1] instanceof Story); // true
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.