Is there a way to "get" the value a document's field in the subdocuments?
book_id is in the main document,how to get the value of it here
'''
const ExtraElements_Schema = new Schema({
label : {type : String, requires : true},
page : {type : Number},
id_resource : {type : Number, required : true},
description : {type : String}
},{toJSON : {virtuals : true , getters : true}})
ExtraElements_Schema.virtual('path').get(function(){
const host = global.gConfig.thisServerHost;
return `${host}/${this.book_id???}/${this.id_resource}`
})
const Extra_Schema = new Schema({
label : {type : String, required : true},
book_id : {type : Number},
id_extra : {type : Number, required : true},
extras : [ExtraElements_Schema]
})
You can use virtuals for this too.
ExtraElements_Schema.virtual('book', {
ref: bookTableName,
localField: 'book_id',
foreignField: '_id', // Change this if it's not the id that is saved
justOne: true
});
And one thing that bugged me a little I couldn't see the virtuals with console.log I should always use console.log(model.toJSON()) to see the virtuals
Related
postSchema
let postSchema = new mongoose.Schema({
data : Buffer,
contentType : String,
caption : String,
likes : [mongoose.ObjectId],
likesCount : {type :Number, default : 0},
comment :[{userId :mongoose.ObjectId, cmnt : String, reply :[{}]}],
commentCount : {type :Number, default : 0},
date : {type : Date, default: Date.now}
})
userSchema
let userSchema = new mongoose.Schema({
qr : {
data : Buffer,
contentType : String
},
profile_pic:{
data:Buffer,
contentType : String
},
first_name:String,
last_name:String,
email:{
type:String,
unique:true
},
mobile_number:Number,
DOB : Date,
gender:{
type : String,
enum : ["Male","Female","Other"]
},
password : {
type : String
},
address:{
city : String,
state : String
},
followers : {
type : [mongoose.ObjectId]
},
followersCount : {
type : Number,
default : 0
},
following : {
type : [mongoose.ObjectId]
},
followingCount : {
type : Number,
default : 0
},
//this is my post schema
posts : [postSchema],
postsCount :{type :Number, default : 0},
reset_password_token : {
OTP:Number,
is_varify_password_token : {
type:Boolean,
default : false
},
time : {
type : Date,
}
}
})
** 1) i want to find specific user
2) after finding user i want to find and update specific post (caption) in array of posts **
i have tried but not working
await USERMODEL.findOneAndUpdate({_id:req.user._id,posts:{$elemMatch:{_id: req.params.postId}}},{"posts.$.caption ":caption})mongodb document image
PLEASE HELP I AM NEW TO MONGODB
**by mistake I have pasted some code out of block please do not mind **
It looks like your post is mostly code; please add some more details
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var patientSchema = new Schema({
resourceType : {type :String, default : 'Patient' },
id : {type : String, default : 'example'},
text : [{
status : {type : String, default : 'generated'},
div :{type : String, default :'<div> Something </div>'}
}],
active : {type : String, default : 'true'},
identifier : [{
use : {type : String, default : 'official'},
system : {type : String, default : 'urn:oid:1.2.36.146.595.217.0.1'},
assinger :[{
display : {type : String, default : 'Acme Healthcare'},
}]
}],
name: [{
use : {type : String, default : 'official'},
first_name : {type : String, default : ''},
second_name : {type : String, default : ''}
}],
gender :{type : String, default : ''},
birthDate :{type : String, default : ''},
telecom : [{
system : {type : String, default : ''},
value : {type : String, default : ''}
}],
address : [{
use : {type : String, default : 'official'},
text : {type : String, default : ''},
city : {type : String, default : ''},
district : {type : String, default : ''},
state : {type : String, default : ''},
postalcode :{type : String, default : ''}
}]
});
var patients = mongoose.model('Patients',patientSchema);
module.exports = patients;
This is my model class, i'm sending values through post-man tool,
The default values inside the array of fields eg.
text : [{
status : {type : String, default : 'generated'},
div :{type : String, default :'<div> Something </div>'}
}],
the status and div are not storing the default values
i need to store the values of status and div as default!
You could use a sub-scheme/document instead!
var patientTextSchema = new Schema({
status : {type : String, default : 'generated'},
div :{type : String, default :'<div> Something </div>'}
});
... ommited for clarity
var patientSchema = new Schema({
text: [patientTextSchema]
})
This way you you can do patient.text.push({}) for adding a default patientTextSchema, or patient.text.push({status: "another_status"}) for a (partially) filled scheme.
Source: http://mongoosejs.com/docs/subdocs.html
You can use the following way to create Array of Objects with a default in mongoose:
const organisationSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
brands: {
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'brand'
}
],
default: []
},
users: {
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}
],
default: []
}
}, { timestamps: true });
Here's the schema:
var RdvSchema = new Schema({
_idRdv: Schema.Types.ObjectId,
patient:{type: Schema.Types.Mixed, ref:'Patient'} ,
pro: {type: Schema.Types.Mixed, ref:'Pro'},
motif: {type: Schema.Types.Mixed, ref: 'Pro'},
domicile:{type: Schema.Types.Mixed, ref: 'Pro'},
}
Here's the data:
var rdv1 = new Rdv({
_idRdv: new mongoose.Types.ObjectId(),
patient: patient1.name,
pro: pro1.name,
motif: pro1.Consultation.Motif,
domicile: pro1.Consultation.Domicile
});
And here's the shell:
MongoDB Enterprise > db.rdvs.find().pretty()
{
"_id" : ObjectId("59c28817f81e91061044ddc7"),
"_idRdv" : ObjectId("59c28817f81e91061044ddc6"),
"patient" : "Maxime",
"pro" : "Ben",
"domicile" : true,
"__v" : 0
How can I prevent this : "_id" : ObjectId("59c28817f81e91061044ddc7") from happening?
"_id" is the unique identifier for any mongodb document. You cannot make it not generated in a document.
But you can remove it in your output of the find as below:
db.rdvs.find({}, {'_id': False}).pretty()
I have this model
//user notif schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserNotifSchema = new mongoose.Schema({
NotifType : {type : Number},
NotifData : {
User_source_id : {type : Schema.Types.ObjectId, ref : 'User'}, // for course, forking
Course_id : {type : Schema.Types.ObjectId, ref : 'Course'}, // for course
UserFile_id : {type : Schema.Types.ObjectId, ref : 'UserFile'} // for forking
},
NotifTarget : [
{type : Schema.Types.ObjectId, ref : 'User'}
],
Created_at : {type : Date, required : true, default : Date.now},
});
var UserNotif = mongoose.model('UserNotif', UserNotifSchema);
module.exports = UserNotif;
I create a model that contains user notification by NotifTarget. I want to get some notif to specific user and doing like this
var user_id = req.session.userLogin.UserId;
NotifModel.find({'NotifTarget' : user_id})
.populate('NotifTarget')
.exec(function(err, doc){
if (err){
res.send(err);
}
else{
res.send(doc);
}
})
This is ok when there only one array user_id in NotifTarget but return empty array when I give multiple data in NotifTarget. Are there any solution for this?
I want the output to be like this
var FeedSchema = new Schema({
timestamp : {type : String, required : true},
feed_type_code : {type : Number, required : true},
gender : {type : String, required : true},
feed_item : Article || Tip || etc.
}
Hence, I understand I have to use discriminators. I followed the following SO answer
Here is what I did:
var feed_type = {discriminatorKey : 'feed_item'};
var FeedSchema = new Schema({
timestamp : {type : String, required : true},
feed_type_code : {type : Number, required : true},
gender : {type : String, required : true}
}, feed_type);
var TipSchema = new Schema({
tip : {type : String, required : true},
subtip : {type : String, required : true},
display_count : {type : Number},
likes : {type : Number}
}, feed_type);
var ArticleSchema = new Schema({
title : {type : String, required : true},
english_title : {type : String, required : true},
image_url : {type : String, required : true},
article_text : {type : String, required : true},
english_article_text : {type : String},
author : {type : String},
english_author : {type : String}
}, feed_type);
Here is how I am saving the document:
var article = new Article({
title : req.body.title,
english_title : req.body.english_title,
image_url : req.body.image_url,
article_text : req.body.article_text,
english_article_text : req.body.english_article_text,
author : req.body.author,
english_author : req.body.english_author
});
var feed = new Feed({
gender : req.body.gender,
timestamp : moment().valueOf(),
feed_type_code : 9002,
feed_item : article
});
feed.save(function(err, doc){
if(err){
res.json({success : -1});
return;
}
res.json({success : 1, feed : doc});
});
I am not getting the article output for this:
{
"success": 1,
"feed": {
"__v": 0,
"gender": "female",
"timestamp": "1481460218959",
"feed_type_code": 9002,
"_id": "584d49faa6ff3a23bc868ab3"
}
}
I am new to Nodejs. I would appreciate if you can point out the error.
in the model file add these lines
var Feed = mongoose.model('Feed', FeedSchema, 'feed');
var Article = Feed.discriminator('Article', ArticleSchema);
var Tip = Feed.discriminator('Tip', TipSchema);
module.exports = {
Feed : Feed,
Article : Article,
Tip : Tip
}
This is how you save the document. You don't need to create a separate Feed object.
var article = new Article({
gender : req.body.gender,
timestamp : moment().valueOf(),
feed_type_code : 9002,
title : req.body.title,
english_title : req.body.english_title,
image_url : req.body.image_url,
article_text : req.body.article_text,
english_article_text : req.body.english_article_text,
author : req.body.author,
english_author : req.body.english_author
});
article.save(function(err, doc){
if(err){
console.log(err);
res.json({success : -1});
return;
}
res.json({success : 1, feed : doc});
});