Trying to do a simple CRUD for a user.
I am passing name, email, password, location, avatar through a sign up form from React/Redux.
I am getting an error during the save which says the following about a duplicate key error --
(node:30190) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error index: heroku_10vr0vgl.users.$googleId_1 dup key: { : null }","op":{"avatar":"avatar.jpg","slug":"jane","id":"cj7nl39w50000amcaool50zcp","name":"Jane","email":"admin#jane.com","password":"$2a$10$envMKYq6xFCkZGpYVd4rEel4g5TGijFOEnr.ayMymHM1ph0/1luGC","location":"Los Angeles","_id":"59bd5e9478537875ee6b8939","createdAt":"2017-09-16T17:25:40.863Z","campaigns":[],"role":"NORMAL","__v":0}})
Looks to be something about a duplicate val, but googleID for ex is not required.
I only have a mock user in the user collection that looks like the following --
[
{
"_id": {
"$oid": "59a070dea4de3af502af7d5c"
},
"avatar": "avatar.jpg",
"name": "John Doe",
"role": "ADMIN",
"slug": "john-doe",
"id": "1",
"email": "admin#johndoe.com",
"location": "Los Angeles",
"campaigns": ["1"],
"twitterId": "refinery29",
"password": "test1234"
}
]
The user model looks like the following --
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {type: 'String', required: true},
role: {type: 'String', default: 'NORMAL', required: true},
location: {type: 'String'},
slug: {type: 'String', required: true, index: {unique: true, dropDups: true}},
campaigns: {type: ['String'], default: []},
avatar: {type: 'String', required: true},
email: {type: 'String', index: {unique: true, dropDups: true}},
id: {type: 'String', required: true, index: {unique: true, dropDups: true}},
googleId: {type: 'String'},
facebookId: {type: 'String'},
twitterId: {type: 'String'},
createdAt: {type: 'Date', default: Date.now, required: true},
password: {type: 'String'},
});
export default mongoose.model('User', userSchema);
Looks like I had an existing index reference. I dropped my user collection and saved. All is well!
Related
I've been writing a lot of MySQL lately so I've forgotten how to write some Mongoose queries. I am trying to search my database to find stocks where the user is the same as the req.params.user. below is the route and my Schema so you can see what's going on. I'm running it in Post man, but it's giving me a "Cannot GET /stock/user-stocks/Sina" Error. I also left a sample stock in my DB for reference
router.get('user-stocks/:user', (req, res) => {
Stock.find({ user: toString(req.params.user)})
.then((stocks) => res.json(stocks))
.catch(err => res.json(err))
})
const stockSchema = new Schema({
user: {type: String, required: true},
symbol: {type: String, required: true},
target: {type: Number, required: false},
stop: {type: Number, required: false},
description: {type: String, required: false},
date: {type: Date, required: false}
})
{
"_id": "5ff284d07b93cd434cae9a08",
"user": "Sina",
"symbol": "AAPL",
"target": 200,
"stop": 100,
"description": "Get money",
"date": "2021-01-03T00:00:00.000Z",
"__v": 0
},
so I have this kind of model
const vetSchema = new mongoose.Schema({
username: {type: String, required: true, trim: true, unique: true},
email: {type: String, unique: true, trim: true,},
expYear: {type: Number},
KTP: {type: String, unique: true, trim: true},
cert_id: {type: String, unique: true, trim: true, select: false},
})
const clinicSchema = new mongoose.Schema({
vet: [{type: mongoose.Schema.Types.ObjectID, ref: 'vet'}],
)}
what I want to do is finding vet by username, which the vet ID is not included in the clinic based on clinic ID, the query to find the vet is {username: {$regex: (?i)${keyword}.*}}
for example, we have this data
Clinic = [{
"_id" : ObjectId("5e57a45836d300b188f4444a"),
"vet": [ObjectId("5e0742fc9d4b20100f89b626"),ObjectId("5e53698fd2b9ee43e7693e01")]
}]
Vet = [
{
"_id" : ObjectId("5e0742fc9d4b20100f89b626"),
"username": "VetClinic"
},
{
"_id" : ObjectId("5e55df62576bc9811877033e"),
"username": "VetNotClinic"
},
{
"_id" : ObjectId("5e53698fd2b9ee43e7693e01"),
"username": "VetClinic"
},
]
what i want is if I find Vet it only shows VetNotClinic because VetClinic is included in the clinic's ID, any good query / agregate?
you can use $nin to query where a field is "not in" an array like so
Vet.find({
username: {$regex: (?i)${keyword}.*},
_id: {$nin: clinic.vet}
})
I have a User Schema, which has multiple notes, and the Note which belongs to a userId
const UserSchema = new Schema({
_id: Schema.Types.ObjectId,
email: {type: String, required: true, trim: true, lowercase: true, unique: true},
notes: [{type: Schema.Types.ObjectId, ref: 'Note'}]
});
const NoteSchema = new Schema({
userId: {type: mongoose.Types.ObjectId, ref: 'User'},
content: {type: String, required: true, trim: true, lowercase: true},
});
I'm trying to populate my User with the notes using the following syntax (from the docs)
const user = await User.findById(mongoose.Types.ObjectId("5bd2a8c4963ac00f57a18074"))
.populate('notes')
.exec(function (err, result) {
console.log(result);
});
But it's returning the User without the Notes data. Any idea what I might be doing wrong?
NoteSchema here is the problem:
userId: {type: mongoose.Types.ObjectId, ref: 'User'}
Use below,
userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
// OR
userId: {type: Schema.Types.ObjectId, ref: 'User'}
// OR
userId: {type: Schema.ObjectId, ref: 'User'} // For backword compatibility
Note:- The schema should always use mongoose.Schema.Types. And mongoose.Types.ObjectId can be used withing mongoose implementation.
I am able to get document properly (Below code):
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
const NoteSchema = new Schema({
userId: {type: Schema.Types.ObjectId, ref: 'UserTest'},
content: {type: String, required: true, trim: true, lowercase: true},
});
const UserSchema = new Schema({
_id: Schema.Types.ObjectId,
email: {type: String, required: true, trim: true, lowercase: true, unique: true},
notes: [{type: Schema.Types.ObjectId, ref: 'NoteTest'}]
});
var Note = mongoose.model('NoteTest', NoteSchema);
var User = mongoose.model('UserTest', UserSchema);
User.find({_id : mongoose.Types.ObjectId("5bd2c84dd79cc5d8b1c62964")})
.populate('notes')
.exec(function (err, result) {
console.log("result.....", JSON.stringify(result));
});
Output:
[
{
"_id": "5bd2c84dd79cc5d8b1c62964",
"email": "hardik#com.com",
"notes": [
{
"_id": "5bd2c869d79cc5d8b1c62965",
"content": "ABC",
"userId": "5bd2c84dd79cc5d8b1c62964"
},
{
"_id": "5bd2c88ad79cc5d8b1c62966",
"content": "DEF",
"userId": "5bd2c84dd79cc5d8b1c62964"
}
]
}
]
How find comment inside commentUnders?
comments: [{
nickName: {type: String, required: true},
comment: {type: String, required: true},
commentUnders: [{
nickName: {type: String, required: true},
comment: {type: String, required: true},
}]
}]
I tried this but it did not work.
Post.findOne({'comments._id' : req.body._idComment},
{'comments._id': $elemMatch: req.body._idComment,
'commentUnders._id': $elemMatch: req.body._idCommentUnders}, function(err, data) {
console.log(data);
});
I have a simple app which lists tour guides and reviews left by users about each guide. Any user can give be a guide and can give reviews. My scheme for a user is:
var User = new mongoose.Schema({
firstName: { type: String, required: true, unique: true },
lastName: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true}
isGuide: Boolean,
rating: {type: Number, "default": 0, min: 0, max: 5},
reviews: [reviewSchema]
});
var Review = new mongoose.Schema({
userId: {type: Schema.ObjectId, ref: 'User'},
author: {type: String, required: true},//contatenation of firstName and lastName of user that wrote review
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: {type: String, required: true},
createdOn: {type: Date, "default": Date.now}
});
mongoose.model('User', User);
I want to be able to:
1/ show a guide and all that guide's reviews
2/ show all a user's reviews
3/ show all guides a user has reviewed
I think my schema above is fine for 1. But is it suitable for 2 and 3? Am I understanding the MonboDB philosophy correctly?