i have a mongodb collection named Feed and it has an attribute named "type". according to that string, i want to send a changeable fields with json. For example if type is "photo" i want to do somethig like that
schema.find({number: "123456"},"body number",
function(err, data) {
but if the string is story, instead of photo; İn the same 'schema.find' query,it should create a json with "body url" instead of "body number". and they all should be passed with the same json.
res.json(data);
For a clear example, i want my json to be like this. as you se the fields change according to "type". but they are all actually in the same collection.
[
{
type: 'photo',
number: 123456,
url: 'asd.jpg',
},
{
type: 'story',
body: 'hello',
number: 123456,
}
]
So basically you want to return certain documents fields from the Feed collection, which are specified in a variable like e.g. "firstName pic points photos"
.
Are there Feed documents with the story
field?
The Model.find() does not create any schema.
Maybe edit with further code so we can understand the command.
For document-specific JSON formatting like this, you can override the default toJSON
method of your Feed
model as shown in this gist.
UPDATE
If you want this sort of flexibility in your documents then it's even easier. Just define your schema to include all possible fields and then only set the fields that apply to given document for its type
. The fields that you don't use won't appear in the document (or in the JSON response). So your schema would look like:
var feedSchema = new Schema({
type: { type: 'String' },
venue: Number,
url: String,
body: String
});
Take a look to mongoose-schema-extend. Using the 'Discriminator Key' feature, you can instruct .find() to create the proper model in each individual case.
Your code should look like this (not tested):
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
});