MongoDb unable to populate user - database

Hi I am trying to populate user into another schema called feedbackschema.
Feedback schema
const mongoose = require('mongoose');
const {
Schema,
} = mongoose;
// Create Schema
const FeedbackSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users',
},
pro: {
type: String,
required: true,
},
con: {
type: String,
required: true,
},
comments: {
type: String,
required: true,
},
rating: {
type: String,
required: true,
},
});
// Create model
const feedback = mongoose.model('feedbacks', FeedbackSchema);
module.exports = feedback;
User Schema
const mongoose = require('mongoose');
const {
Schema,
} = mongoose;
// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
},
password: {
type: String,
required: true,
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
});
// Create a model
const user = mongoose.model('users', UserSchema);
// Export the model
module.exports = user;
and here is my controller where I am trying to populate the user
getAllFeedbacks: async (req, res) => {
const errors = {};
try {
const feedbacks = await Feedback.find().populate('user');
return res.json(feedbacks);
} catch (err) {
errors.noFeedbacks = 'Please try again';
return res.status(404).json(errors);
}
},
Json I am receiving through postman is this
[
{
"_id": "5b3adf88f3c4cd836bdc2eda",
"pro": "knfklngfdklgnfdgknkln",
"con": "Sales executive updates",
"comments": "This is a another funfact for me is me too",
"rating": "8",
"__v": 0
}
]
It is supposed to show user key but somehow its not working. I checked the current user data is already there but for some reason its not pushing the user info feedback object.
FeedBack collection
[
{
"_id": {
"$oid": "5b3adf88f3c4cd836bdc2eda"
},
"pro": "knfklngfdklgnfdgknkln",
"con": "Sales executive updates",
"comments": "This is a another funfact for me is me too",
"rating": "8",
"__v": 0
}
]
User Collection
[
{
"_id": {
"$oid": "5b37e456565971258da97d5e"
},
"isAdmin": false,
"name": "montygoldy",
"email": "montygoldy#gmail.com",
"password": "$2a$10$zWbxV0Q3VPUxRC6lzJyPBec3P/8zYBaSCTJ2n88Uru3zzFlicR2rq",
"__v": 0
}
]

Related

methods.myFunction().call() throws Returned values aren't valid, did it run Out of Gas? Error

I am using "web3": "1.0.0-beta.26" and is getting the following error...
Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
I have rerun truffle migrate --reset and used the address generated as the TODO_LIST_ADDRESS but I am still getting the error above
Anyone encountered this before and knows how to solve it? Thanks
App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
account: "test",
taskCount: 0
};
}
componentDidMount() {
this.loadBlockchainData();
}
loadBlockchainData = async () => {
const ethereum = window.ethereum;
ethereum.autoRefreshOnNetworkChange = false;
const web3 = window.web3;
const web3Instance = new Web3(ethereum);
const enabledWeb3 = await ethereum.enable();
const accounts = await web3Instance.eth.getAccounts();
const accountAddress = await accounts[0];
this.setState({ account: accountAddress });
const todoList = new web3Instance.eth.Contract(
TODO_LIST_ABI,
TODO_LIST_ADDRESS
);
console.log("todoList ", todoList);
//! ERROR
const taskCount = await todoList.methods.taskCount().call();
console.log("taskCount ", taskCount);
this.setState({ taskCount });
};
render() {
return (
<div className="container">
<h1>Hey World</h1>
<p>Your Account: {this.state.account}</p>
<p>Task Count: {this.state.taskCount}</p>
</div>
);
}
}
export default App;
config.js
export const TODO_LIST_ADDRESS = "0xb0D64f6C317448efa56A33678d718Fd715DAeddd";
export const TODO_LIST_ABI = [
{
inputs: [],
payable: false,
stateMutability: "nonpayable",
type: "constructor"
},
{
constant: true,
inputs: [],
name: "taskCount",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [
{
internalType: "uint256",
name: "",
type: "uint256"
}
],
name: "tasks",
outputs: [
{
internalType: "uint256",
name: "id",
type: "uint256"
},
{
internalType: "string",
name: "content",
type: "string"
},
{
internalType: "bool",
name: "completed",
type: "bool"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: false,
inputs: [
{
internalType: "string",
name: "_content",
type: "string"
}
],
name: "createTask",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function"
}
];

How to increment property's value(integer) inside .update() and $set mongoose?

I'm trying to find a document in my database using findOne() and then search that document for options array that contains objects. Then I check object's property if it's equal to pollOption then I want to increment that object's another property votes by 1, but I can't get that property's value so I can increment it. Please help.
Routes.js
router.post('/submitVote', function(req, res){
const {pollId, pollOption} = req.body;
Polls.findOne({_id: pollId}
).update({'options.option': pollOption}, {'$set': {
'options.$.votes': '', // INCREMENT BY 1 //
}}, function(err){
if(err){
return console.log(err);
} else {
return res.send('success');
}
});
});
Sample Model:
{
"_id": {
"$oid": "5b2ec4852a51d06734f71e79"
},
"options": [
{
"option": "Amazing!",
"votes": 0
},
{
"option": "Good.",
"votes": 0
}
],
"creator": "Guest",
"name": "Rate this website!",
"__v": 0
}
Polls.js - Schema
var mongoose = require('mongoose');
const Poll = new mongoose.Schema({
name: { type: String, required: true },
options: { type: Array, required: true },
creator: { type: String, default: 'Guest' }
});
const Polls = mongoose.model('Polls', Poll);
module.exports = Polls;

Trouble Adding objects to MongoDB array [duplicate]

Basically I have a mongodb collection called 'people'
whose schema is as follows:
people: {
name: String,
friends: [{firstName: String, lastName: String}]
}
Now, I have a very basic express application that connects to the database and successfully creates 'people' with an empty friends array.
In a secondary place in the application, a form is in place to add friends. The form takes in firstName and lastName and then POSTs with the name field also for reference to the proper people object.
What I'm having a hard time doing is creating a new friend object and then "pushing" it into the friends array.
I know that when I do this via the mongo console I use the update function with $push as my second argument after the lookup criteria, but I can't seem to find the appropriate way to get mongoose to do this.
db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});
Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };
There are two options you have:
Update the model in-memory, and save (plain javascript array.push):
person.friends.push(friend);
person.save(done);
or
PersonModel.update(
{ _id: person._id },
{ $push: { friends: friend } },
done
);
I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).
However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the latter when it's absolutely necessary.
The $push operator appends a specified value to an array.
{ $push: { <field1>: <value1>, ... } }
$push adds the array field with the value as its element.
Above answer fulfils all the requirements, but I got it working by doing the following
var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
People.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { friends: objFriends } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
)
Another way to push items into array using Mongoose is- $addToSet, if you want only unique items to be pushed into array. $push operator simply adds the object to array whether or not the object is already present, while $addToSet does that only if the object is not present in the array so as not to incorporate duplicacy.
PersonModel.update(
{ _id: person._id },
{ $addToSet: { friends: friend } }
);
This will look for the object you are adding to array. If found, does nothing. If not, adds it to the array.
References:
$addToSet
MongooseArray.prototype.addToSet()
Use $push to update document and insert new value inside an array.
find:
db.getCollection('noti').find({})
result for find:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
update:
db.getCollection('noti').findOneAndUpdate(
{ _id: ObjectId("5bc061f05a4c0511a9252e88") },
{ $push: {
graph: {
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
}
})
result for update:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
First I tried this code
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
}
);
But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element !
So the simple solution is written below
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
{ upsert: true }
);
Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements !
The upsert = true option creates the object if it doesn't exist. default is set to false.
if it doesn't work use below snippet
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
).exec();
An easy way to do that is to use the following:
var John = people.findOne({name: "John"});
John.friends.push({firstName: "Harry", lastName: "Potter"});
John.save();
In my case, I did this
const eventId = event.id;
User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();
Push to nested field - use a dot notation
For anyone wondering how to push to a nested field when you have for example this Schema.
const UserModel = new mongoose.schema({
friends: {
bestFriends: [{ firstName: String, lastName: String }],
otherFriends: [{ firstName: String, lastName: String }]
}
});
You just use a dot notation, like this:
const updatedUser = await UserModel.update({_id: args._id}, {
$push: {
"friends.bestFriends": {firstName: "Ima", lastName: "Weiner"}
}
});
This is how you could push an item - official docs
const schema = Schema({ nums: [Number] });
const Model = mongoose.model('Test', schema);
const doc = await Model.create({ nums: [3, 4] });
doc.nums.push(5); // Add 5 to the end of the array
await doc.save();
// You can also pass an object with `$each` as the
// first parameter to use MongoDB's `$position`
doc.nums.push({
$each: [1, 2],
$position: 0
});
doc.nums;
// This is the my solution for this question.
// I want to add new object in worKingHours(array of objects) -->
workingHours: [
{
workingDate: Date,
entryTime: Date,
exitTime: Date,
},
],
// employeeRoutes.js
const express = require("express");
const router = express.Router();
const EmployeeController = require("../controllers/employeeController");
router
.route("/:id")
.put(EmployeeController.updateWorkingDay)
// employeeModel.js
const mongoose = require("mongoose");
const validator = require("validator");
const employeeSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please enter your name"],
},
address: {
type: String,
required: [true, "Please enter your name"],
},
email: {
type: String,
unique: true,
lowercase: true,
required: [true, "Please enter your name"],
validate: [validator.isEmail, "Please provide a valid email"],
},
phone: {
type: String,
required: [true, "Please enter your name"],
},
joiningDate: {
type: Date,
required: [true, "Please Enter your joining date"],
},
workingHours: [
{
workingDate: Date,
entryTime: Date,
exitTime: Date,
},
],
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
const Employee = mongoose.model("Employee", employeeSchema);
module.exports = Employee;
// employeeContoller.js
/////////////////////////// SOLUTION IS BELOW ///////////////////////////////
// This is for adding another day, entry and exit time
exports.updateWorkingDay = async (req, res) => {
const doc = await Employee.findByIdAndUpdate(req.params.id, {
$push: {
workingHours: req.body,
},
});
res.status(200).json({
status: "true",
data: { doc },
});
};
https://www.youtube.com/watch?v=gtUPPO8Re98
I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.
---- Person model
const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema = mongoose.Schema;
const productSchema = new Schema({
friends : [SingleFriend.schema]
});
module.exports = mongoose.model('Person', personSchema);
***Important: SingleFriend.schema -> make sure to use lowercase for schema
--- Child schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SingleFriendSchema = new Schema({
Name: String
});
module.exports = mongoose.model('SingleFriend', SingleFriendSchema);

how to push data in inside array mongodb?

i am trying to push array in document array my collection is
{
"_id": "58eed81af6f8e3788de703f9",
"first_name": "abc",
"vehicles": {
"exhibit": "18",
"title": "Motor Velicle Information for Donald French",
"details": [
{
"year": "",
"make_model": "",
"registered_owner": "",
"license_number": "",
"date_of_purchase": "",
"purchase_price": ""
}
]
}
}
so what i want is to push data in details for that i had try like this
Licensee.update({"_id":"58eed81af6f8e3788de703f9"},{
$push:{
"vehicles.details":data
}
},function(err,data){
if(!err)
{
console.log('data',data);
}
else
{
console.log('err',err);
}
});
and for this i create one schema i don't know is right or not
var licSchema = new SimpleSchema({
"_id":{
type:String,
label:"_id",
optional: false,
},
"vehicles.details.year": {
type: String,
label: "year",
optional: true,
},
"vehicles.details.make_model": {
type: String,
label: "make_model",
optional: true,
}
});
where is my fault please give me solution .
Error Uncaught Error: After filtering out keys not in the schema, your modifier is now empty
You can try this. AddToSet should be the right way.
const schema = new SimpleSchema({
"vehicles.details.$.year": {
type: String,
label: "year",
optional: true,
},
"vehicles.details.$.make_model": {
type: String,
label: "make_model",
optional: true,
}
});
Licensee.update({"_id":"58eed81af6f8e3788de703f9"},{
$addToSet:{
"vehicles.details": data
}
});

How to remove Object from array using mongoose

I'm trying to remove an object from an array in a document using mongoose.
The Schema is the following:
var diveSchema = new Schema({
//irrelevant fields
divers: [{
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
meetingLocation: { type: String, enum: ['carpool', 'onSite'], required: true },
dives: Number,
exercise: { type: Schema.Types.ObjectId, ref: 'Exercise' },
}]
});
a possible entry can be
{
//irrelevant fields
"divers": [
{
"_id": "012345678",
"user": "123456789",
"meetingLocation": "carpool",
"exercise": "34567890",
},
{
"_id": "012345679",
"user": "123456780",
"meetingLocation": "onSite",
"exercise": "34567890",
}
]
}
Say I want to remove the entry where user is 123456789 (note I do not know the _id at this point).
How do I do this correctly?
I tried the following:
var diveId = "myDiveId";
var userIdToRemove = "123456789"
Dive.findOne({ _id: diveId }).then(function(dive) {
dive.divers.pull({ user: userIdToRemove });
dive.save().then(function(dive) {
//do something smart
});
});
This yieled no change in the document.
I also tried
Dive.update({ _id: diveId }, { "$pull": { "divers": { "diver._id": new ObjectId(userIdToRemove) } } }, { safe: true }, function(err, obj) {
//do something smart
});
With this I got as result that the entire divers array was emptied for the given dive.
What about this?
Dive.update({ _id: diveId }, { "$pull": { "divers": { "user": userIdToRemove } }}, { safe: true, multi:true }, function(err, obj) {
//do something smart
});
I solve this problem using this code-
await Album.findOneAndUpdate(
{ _id: albumId },
{ $pull: { images: { _id: imageId } } },
{ safe: true, multi: false }
);
return res.status(200).json({ message: "Album Deleted Successfully" });
Try this
Dive.update({ _id: diveId },{"$pull": { "drivers": {"user": "123456789"}}})
Try this async code
var diveId = "myDiveId";
var userIdToRemove = "123456789"
const dive=await Dive.findOne({ _id: diveId })
await dive.divers.pull({ user: userIdToRemove });
await dive.save();
Use this with try/catch:
await Group.updateOne(
{ _id: groupId },
{ $pull: { members: {id: memberId }}}
);

Resources