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
Related
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 });
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});
});
I'm getting a duplicate key error and not sure why.
I have the following schema:
var walletSchema = mongoose.Schema({
currencyName : {type : String, required : true, unique : true},
amount : {type : Number, default : 0}
}, {strict : false});
// define the schema for our user model
var userSchema = mongoose.Schema({
local : {
username : { type: String, required: true, unique: true },
password : { type: String, required: true, unique : true },
email : { type: String, required: true, unique: true },
country : { type: String, required: true },
inventory : {
food : { type : Number, default : 0},
energyDrinks : { type : Number, default : 0 }
},
wallet : [walletSchema],
lastAttackedAt : { type: Date, default: Date.now },
lastJobChange : {type: Date, default: '03/30/1988' },
lastWorked : {type: Date},
referredBy : {type : String, default : 'Admin'},
energy : { type: Number, default: 100 },
energyUpdatedAt : { type : Date, default: Date.now },
resetPasswordToken: String,
resetPasswordExpires: Date
}
},{timestamps : true});
I create a new user with this code :
...
newUser.local.username = capitalizeUser(username);
newUser.local.password = newUser.generateHash(password);
newUser.local.email = req.body.email;
newUser.local.country = req.body.country;
newUser.local.wallet.push({
// Create the default currencies
currencyName: 'Euro',
}, {
currencyName: 'Gold',
}, {
currencyName: result.countryCurrency
}
);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
Everything works fine for the first user however if I try to make another user I get MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: xyz.users.$local.wallet.currencyName_1 dup key: { : "Euro" }.
Why is this happening, doesn't each user has it's own wallet? How should I handle it, keep in mind that there are about ~230 currencies available for each user.
currencyName : {type : String, required : true}
Remove unique from there and you will be good to go. Mongo checks unique keys for collection. In your case walletSchema collection will have a lot of same values so that's why it's gives error.
As your currencyName has been set unique so it has to be different for each user you save. In fact you with this schema you won't even be able to have two users from the same country.
So to avoid this you need to remove the unique keyword from you schema and it is done. It then looks something like this.
var walletSchema = mongoose.Schema({
currencyName : {type : String, required : true},
amount : {type : Number, default : 0}
}, {strict : false});
This question already has answers here:
Stop Mongoose from creating _id property for sub-document array items
(7 answers)
Closed 7 years ago.
I would like to add an element in an array in a mongo database:
db.keypairs.update( {pubkey: "1234567890"}, { $push: {listTxId: {txHash: "yyy", spent: false} } } )
The result is perfect:
listTxId" : [ { "txHash" : "xxx", "spent" : true },{ "txHash" : "yyy", "spent" : false } ]
Now I would like to do the same with node.js and mongoose
var res = wait.forMethod(Keypair,'update', {pubkey: "1234567890"}, { $push: { "listTxId": {"txHash":"zzz", "spent":false} } } );
Keypair is my node.js model for the mongoose collection:
var Keypair = require('./app/models/Keypair');
and wait.forMethod comes from a node module:
var wait = require('wait.for');
In the result, I have this "_id" element :
{ "txHash" : "zzz", "spent" : false, "_id" : ObjectId("56561571fea5d9a10a5771fd") }
QUESTION: where this ObjectId come from ? How can I get rid of it ?
UPDATE: mongoose schema:
var keypairSchema = mongoose.Schema({
userId : { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
pubkey : String,
privkeyWIF : String, // temp
balance : Number,
listTxId : [{
txHash : String,
spent : Boolean
}],
walletId : { type: mongoose.Schema.Types.ObjectId, ref: 'Wallet' },
description : { type: String, maxlength: 40 },
comments : String,
isMasterKey : { type: Boolean, default: false },
date : Date
});
Mongoose will put ids in your subdocument arrays. listTxId is a subdocument array. You can add _id: false to your schema to prevent this:
var keypairSchema = mongoose.Schema({
userId : { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
pubkey : String,
privkeyWIF : String, // temp
balance : Number,
listTxId : [{
_id: false,
txHash : String,
spent : Boolean
}],
walletId : { type: mongoose.Schema.Types.ObjectId, ref: 'Wallet' },
description : { type: String, maxlength: 40 },
comments : String,
isMasterKey : { type: Boolean, default: false },
date : Date
});
I have the following schemas in mongoose:
var documentsSchema = new Schema({
"document" : {
"_project" : {
type : Schema.ObjectId,
ref : 'Projects'
},
"_addedBy" : {
type : Schema.ObjectId,
ref : 'Users'
},
"_associateUsers" : [{
type : Schema.ObjectId,
ref : 'Users'
}],
"_codes" : [{
type : Schema.ObjectId,
ref : 'Codes'
}],
"paragraphTitle" : String,
"paragraphText" : String,
"memos" : [
{
"_addedBy" : {
type: Schema.Types.ObjectId,
ref: 'Users'
},
"memoData" : String
}
]}});
and the Codes:
var codesSchema = new Schema({
"code" : {
"_addedBy" : {
type : Schema.ObjectId,
ref : 'Users'
},
"codeText" : String,
"codeWeight" : Number
}});
I need to populate _codes.codeText (or codes fields) of the all elements of the array, but looks like I am not doing it properly.
Documents.find({
"document._project": element._id
}).
populate('document._codes.code','codeText').
exec(function (err, result) { .... }
this and various tries with populate arguments are either not populating the fields or not returning any data.
What am I doing wrong?
You have defined the schema, but not the model. The _codes has a ref to the model Codes but it doesn't exists. When you call .populate with the first two params it assumes that the model is Codes (taked from reference)
To fix this, toy need to add:
mongoose.model('Codes', codesSchema);
mongoose.model('Documents', documentsSchema);
Maybe you need to do the same with Users
See the complete documentation for populate here
P.S. A recommendation: If you are defining an schema for codes or whatever you don't need to define again the name of the object as part of the same schema, look:
From this
//your style
var catsSchema = new Schema({
"cat" : {
"attr1" : {type: ...},
"attr2" : {type: ...}
}
});
to this
//obviously attr1 and attr2 are part of cat object/document
var catsSchema = new Schema({
"attr1" : {type: ...},
"attr2" : {type: ...}
});