I have a json file which stores the data from mongodb in a array format i want to change some fields in it example email, phone number etc.How can i do it using nodejs and faker?
Exaple of one data.json file
{
_id: 54522,
roles: [ [Object] ],
__v: 48,
name: { last: 'Coke', first: 'Colay' },
cv: {
_id: 54522,
updatedAt: Z,
createdAt: 2Z,
educationEntries: [Array],
workEntries: [Array]
},
unverifiedEmail: null,
unverifiedPhoneNumber: null,
phoneNumberVerificationCode: null,
phoneNumber: '8754552512',
password: 'expected',
emailVerificationCode: 'null',
smoochUserId: '2b390',
},
I want to change phonenumber emailverification and unverfiedEmail entries.
Thanks in advance.
Related
I have the following document in MongoDB. How can I find a specific ID inside the likes array and return the populated information of that object?
This is the document:
{ _id: ObjectId("60a90f0e1f4af802e8b893e6"),
status: 'Available',
likes:
[ ObjectId("60a8e0b9baa1572b847931ed"),
ObjectId("60aa342cb6b39e3024453465") ],
name: 'coba',
age: '1 Year',
__v: 0 }
This is the function I have tried but it's returning a 404 error, though as you can see the id actually exists in the likes array.
const [foundUser] = await PetsModel.find(
{
likes: { $in: ["60a8e0b9baa1572b847931ed"] }
},
{ likes: 1 }
).populate({
path: 'likes',
select: {
__v: 0,
createdAt: 0,
updatedAt: 0,
password: 0
}
});
res.status(201).json({
success: true,
data: foundUser.likes
});
There you are telling MongoDB to search a string, not an id. So you have to convert the string into an id so MongoDB can search it. The code should look like this:
const mongoose = require('mongoose');
const [foundUser] = await PetsModel.find(
{
likes: { $in: [ mongoose.Types.ObjectId("60a8e0b9baa1572b847931ed") ] }
},
{ likes: 1 }
).populate({
path: 'likes',
select: {
__v: 0,
createdAt: 0,
updatedAt: 0,
password: 0
}
});
res.status(201).json({
success: true,
data: foundUser.likes
});
Background
Here's part of my User model:
const Group = require("./Group")
...
groups: {
type: [{ type: Schema.ObjectId, ref: Group }],
default: [],
},
And here's my Group model:
module.exports = mongoose.model(
"Group",
new Schema(
{
name: {
type: String,
required: true,
unique: true,
},
/**
* Array of User ObjectIDs that have owner rights on this group
*/
owners: {
type: [{ type: Schema.ObjectId, ref: User }],
default: [],
},
},
{
timestamps: true,
}
)
)
The Code
Here's the code I'm running to try and populate:
const user = await (await User.findOne({ _id: ... })).execPopulate("Group")
console.log(user.groups)
My console.log is outputting an array of object IDs, when I'd like it to output an actual Group document.
Attempted solutions
I've tried changing my ref to be using the string ("Group"), I've tried arranging my query differently, etc. I'm not sure how I'd go about doing this.
Apologies in advance if this is a duplicate, I've done my best to search but can't really find a solution that works for me.
Specifically, what do I need help with?
I'm trying to create a 'link' between a user model and a group model. In my console.log, I expect it to output a Group document; but it outputs an object ID (which is how it's stored raw in the database, meaning that Mongoose isn't transforming it correctly)
When you change execPopulate to populate like:
async function findUserAndPopulate(userId){
const response = await User.findOne({
_id: userId,
}).populate('groups')
console.log("response",response)
}
You got:
{
groups: [
{
owners: [Array],
_id: 5ecc637916a2223f15581ec7,
name: 'Crazy',
createdAt: 2020-05-26T00:31:53.379Z,
updatedAt: 2020-05-26T00:31:53.379Z,
__v: 0
}
],
_id: 5ecc6206820d583b99b6b595,
fullname: 'James R',
createdAt: 2020-05-26T00:25:42.948Z,
updatedAt: 2020-05-26T00:36:12.186Z,
__v: 1
}
So you can access the user.groups
See the doc: https://mongoosejs.com/docs/populate.html
I installed my dependencies on a new computer and it must have updated mongoose.
All my informative results from queries have returned into these messes with a lot of information that may be useful at times but generally is not useful. Very verbose.
So for example when it runs console.log(result) in a query promise, it used to return something like this:
user: {
_id: '2c918aa5-3d5f-4397-8dd9-35c3675f53a2',
email: 'ayeman#gmail.com',
username: 'ayeman',
password: '$2b$10$1sBah/12s12Ox0971221nk5g2s12s11FVRCW',
watching: '',
__v: 0
}
instead now it returns this:
model {
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
.....
*200 plus lines of verbose data*
....
remove: [Function: pull],
_path: 'chats',
isMongooseArray: true,
validators: [],
_schema: [SchemaArray]
],
_id: '2c918aa5-3d5f-4397-8dd9-35c3675f53a2',
email: 'ayeman#gmail.com',
username: 'ayeman',
password: '$2b$10$1sBah/12s12Ox0971221nk5g2s12s11FVRCW',
watching: '',
__v: 0
},
'$init': true
}
I cant for the life of me find the documentation to return it to the old style.
It seems silly to find all my console logs and cut the extra data manually.
Is there a method to change this back? I was looking for something like mongoose.model.options.changeResultsStyle() or something but I cannot find anything
In the new mongoose version it seems as if it defaults to verbose results. Using .lean() on mongoose query methods will return the lean style that the old mongoose version defaulted too.
My example scenario
User.findOne({username: req.body.username }, {friends: 1}, function(err, result) {
if (err) throw err;
console.log(result.friends[1].pending)
res.json(result.friends[1].pending);
}).lean();
{
_id: '2c918aa5-3d5f-4397-8dd9-35c3675f53a2',
friends: [ { confirmed: [Array] }, { pending: [Array] } ],
status: 'offline',
chats: [ { confirmed: [Array] }, { pending: [Array] } ],
email: 'ayeman#gmail.com',
username: 'ayeman',
password: '$2b$10$gq0OrbxulaUBah/O.LhfjuiOx0970brivNStLXnk5gGn0QYRFVRCW',
watching: '',
__v: 0
}
I am using Mongoose 5.1.7 and attempting to create a compound index across multiple text indexes in my defined schema. Here is my schema definition:
const mongoose = require('mongoose');
const alumniSchema = mongoose.Schema({
firstName: {
type: [String],
required: true
},
lastName: {
type: [String],
required: true
},
classYear: {
type: Number,
required: true
},
photoURL: {
type: String,
},
education: [
{
school: {
type: String,
required: true
},
gradYear: {
type: Number,
required: true
},
degreeType: String,
degreeSubject: String,
}
],
jobs: [
{
employer: {
type: String,
required: true
},
position: String,
startDate: Date,
endDate: Date,
isCurrent: Boolean
}
],
contactInfo: {
phoneNumber: {
type: String,
},
email: {
type: String,
}
},
})
alumniSchema.index({ firstName: 'text', lastName : 'text', email: 'text' });
module.exports = mongoose.model('Alumni', alumniSchema);
When I boot up the server, I receive the following error:
MongoError: Index: { v: 2, key: { _fts: "text", _ftsx: 1 }, name: "firstName_text_lastName_text_email_text", ns: "5b3be578c0c6e317f7c1bc2b_test.alumnis", background: true, weights: { email: 1, firstName: 1, lastName: 1 }, default_language: "english", language_override: "language", textIndexVersion: 3 } already exists with different options: { v: 2, key: { _fts: "text", _ftsx: 1 }, name: "firstName_text_lastName_text_classYear_text_education.school_text", background: true, weights: { classYear: 1, education.school: 1, firstName: 1, lastName: 1 }, default_language: "english", language_override: "language", ns: "5b3be578c0c6e317f7c1bc2b_test.alumnis", textIndexVersion: 3 }
I have been messing around with this for a while and evidently previously created an index. When I use the mongo shell to check the indexes that I currently have set up, however, I cannot find the index "firstName_text_lastName_text_classYear_text_education.school_text" referenced by the error message:
> db
test
> db.collection.getIndexes()
[ ]
I am at an impasse--I'm not sure if I've incorrectly created the index, or if I am supposed to drop the index (it doesn't look like Mongoose natively supports a dropIndex() function).
Has anyone else dealt with this issue? Thanks!
Looks like Mongoose dynamically creates the index at runtime. The trick for me was adding:
var Alumni = mongoose.model('Alumni', alumniSchema);
Alumni.collection.dropIndex('firstName_text_lastName_text_classYear_text_education.school_text', function(err, result) {
if (err) {
console.log('Error dropping index!', err);
}
});
and then restarting the server.
THEN I was able to change the index to whatever I wanted. Note that I still needed to add the above code segment and restart the server every time I wanted to update the index.
I need to find the index of the mongoose objectID in an array like this:
[ { _id: 58676b0a27b3782b92066ab6, score: 0 },
{ _id: 58676aca27b3782b92066ab4, score: 3 },
{ _id: 58676aef27b3782b92066ab5, score: 0 }]
The model I am using to compare is a mongoose schema with the following data:
{_id: 5868d41d27b3782b92066ac5,
updatedAt: 2017-01-01T21:38:30.070Z,
createdAt: 2017-01-01T10:04:13.413Z,
recurrence: 'once only',
end: 2017-01-02T00:00:00.000Z,
title: 'Go to bed without fuss / coming down',
_user: 58676aca27b3782b92066ab4,
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false }
I am trying to find the index of the model._user in the array above using the following:
var isIndex = individualScores.map(function(is) {return is._id; }).indexOf(taskList[i]._user);
Where individualScores is the original array and taskList[i] is the task model. However, this always returns -1. It never finds the correct _id in the array.
I guess your problem is related to how _id are returned by your query
If you get _id as String, your code should work, check the snippet below
But if instead, you get ObjectsIds, you have to cast them to String first
var individualScores = [
{ _id: "58676b0a27b3782b92066ab6", score: 0 },
{ _id: "58676aca27b3782b92066ab4", score: 3 },
{ _id: "58676aef27b3782b92066ab5", score: 0 }
]
var task = {
_id: "5868d41d27b3782b92066ac5",
updatedAt: new Date("2017-01-01T21:38:30.070Z"),
createdAt: new Date("2017-01-01T10:04:13.413Z"),
recurrence: 'once only',
end: new Date("2017-01-02T00:00:00.000Z"),
title: 'Go to bed without fuss / coming down',
_user: "58676aca27b3782b92066ab4",
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false
}
var isIndex = individualScores.map(
function(is) {
return is._id;
})
.indexOf(task._user);
console.log(isIndex)
I think your process should working well that you are using just only need to convert 'objectID' to String to compare. Convert using .toString() for both of _id and _user.
like bellow:
var isIndex = individualScores.map(function(is) {
return is._id.toString();
}).indexOf(taskList[i]._user.toString());