I am new to MongoDb, and I have a question about the insertion of data. My mongoose schema for 'user' collection:
var user = new mongoose.Schema({
username : {type: String},
email : {type: String,index: {unique: true}},
password : {type: String},
feed : [{
title : {type: String},
description : {type: String},
latitude : {type:Number},
longitude : {type:Number},
feedImages : [{
imageUrl: {type: String}
}]
}]
});
I want to insert data to the feedimages and my service for that is:
app.post('/uploadFeedImage',function(req,res) {
var _id = req.body._id;
var imageUrl = req.body.imageUrl;
db.user.update(
{"feed._id":_id },
{$push : {
feedImages:{
imageUrl:imageUrl
}
}
},function (err,result) {
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
});
But the data is not inserted into table and no error is shown, I don't know what is the problem.
My user table is shown below:
use $ to push in the matched element of the array. i.e. for which feed._id matches
Try this:
db.user.update(
{"feed._id":_id },
{$push : {
"feed.$.feedImages":{
imageUrl:imageUrl
}
}
},function (err,result) {
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
Edit
$ is update positional operator, which helps update only the element which matches the update criteria. For more info see MongoDB $ operator Documentation.
Related
I need to populate Referenced database in ListView. In this case I need to Show the Designation Name of the User which is the reference in User Model. How do I call it in Flutter to display the Designation name?
My UserSchema is
var UserSchema = new Schema({
'username' : String,
'role_id' : Number,
'designation_id' : {
type: Schema.Types.ObjectId,
ref: 'Designation'
},
'login_id' : String,
'password' : String,
'status' : String,
'company_id' : {
type: Schema.Types.ObjectId,
ref: 'Company'
},
'enable_login' : Number,
'creation_user_id' : {
type: Schema.Types.ObjectId,
ref: 'User'
}, 'update_user_id' : {
type: Schema.Types.ObjectId,
ref: 'User'
},
'creation_dt' : Date,
'update_dt' : Date});
module.exports = mongoose.model('User', UserSchema);
My Destination Model is:
var DesignationSchema = new Schema({
'name' : String,
'designation_id' : Number,
'company_id' : {
type: Schema.Types.ObjectId,
ref: 'Company'
},
'creation_user_id' : {
type: Schema.Types.ObjectId,
ref: 'User'
},
'update_user_id' : {
type: Schema.Types.ObjectId,
ref: 'User'
},
'creation_dt' : Date,
'update_dt' : Date
});
module.exports = mongoose.model('Designation', DesignationSchema);
User Controller List is:
list: function (req, res) {
UserModel.find(function (err, Users) {
if (err) {
return res.status(500).json({
message: 'Error when getting User.',
error: err
});
}
return res.json(Users);
});
},
In Flutter I created a Service for getting all Users
static Future<Users> getAllUsers() async{
try{
final response = await http.get(BASE_URL + USERS);
if(response.statusCode == 200){
return parseUsers(response.body);
}else{
return Users();
}
}catch(e){
print('Error ${e.toString()}');
return Users();
}
}
static Users parseUsers (String responseBody){
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
List<User> users = parsed.map<User>((json) => User.fromJson(json)).toList();
Users _users = Users();
_users.users = users;
return _users;
}
Showing it in Flutter via
Text(users.users[index].username,style: TextStyle(color: Colors.black87, fontWeight: FontWeight.bold, fontFamily: 'Roboto',),)
Text("Email: ${users.users[index].login_id}", style: TextStyle(color: Colors.black87, fontSize: 12,fontFamily: 'Roboto',))
Text("Designation: Estimate Engineer", style: TextStyle(color: Colors.black87,fontSize: 12,fontFamily: 'Roboto',)),
Thank you for your Support.
I guess you need to change the response and implement the schema inside schema concept
here is the link which talks about the schema inside schema on stack overflow
link : Mongoose schema within schema
Your response should look like this.
{
"_id": "5dee58cba34fa96a09d1f049",
"username": "Moin",
"role_id": 1,
"designation_id": {
"_id": "5dee57d4a34fa96a09d1f047",
"name": "Administrator",
"designation_id": 1,
"company_id": "5dee54681fc99665221ec960",
"creation_user_id": "5dee2a859eae3e0a98109d81",
"update_user_id": "5dee2a859eae3e0a98109d81",
"creation_dt": null,
"update_dt": null,
"__v": 0
},
"login_id": "moin#email.com",
"password": "moin123",
"status": "1",
"company_id": "5dee54681fc99665221ec960",
"enable_login": 1,
"creation_user_id": "5dee2a859eae3e0a98109d81",
"update_user_id": "5dee2a859eae3e0a98109d81",
"creation_dt": null,
"update_dt": null,
"__v": 0
},
Insted of storing a ID you should store the whole schema to esaily get the designation,
Hope this helps.
I am trying to insert embedded document in MongoDB through nodejs. This is schema of embedded document
var patientSchema = new mongoose.Schema({
status: {type: String},
message:{type: String},
statusCode:{type: Number},
user: [{
pname: {type : String },
email: {type : String },
password: {type : String },
mobile: {type : String},
otp:{type: Number},
age: {type : String }
}]
})
and here is the code of insertion
router.post('/panel/register', function(req, res){
console.log(req.body.mobile_number+req.body.email);
new patient({
status: "ok",
message:"success",
statusCode:"201",
'user.$.pname': req.body.name,
'user.$.password': req.body.password,
'user.$.email': req.body.email,
'user.$.mobile': req.body.mobile_number
}).save(function(err, doc){
if(err) res.json(err);
else {
res.json({"doc ":doc});
}
})
})
but whenever i am trying to insert data using this code it is showing me this error
{
"code": 11000,
"index": 0,
"errmsg": "E11000 duplicate key error index: rhc.patients.$mobile_1 dup key: { : null }",
"op": {
"status": "ok",
"message": "success",
"statusCode": 201,
"_id": "59f38e4d94fff613fc8c4979",
"user": [],
"__v": 0
}
}
As i am understanding this error is because this is not mapping the values of email, mobile inside the user, can someone help to resolve it, i think i am inserting it in wrong way , please help
Edit:
For clarity: the problem wasn't really the syntax, but rather a unique constraint that was removed, without the database being updated. You can read more about that here and here.
Original answer:
You can do it like this:
router.post('/panel/register', function(req, res){
console.log(req.body.mobile_number+req.body.email);
new patient({
status: "ok",
message:"success",
statusCode:"201",
user: [{
pname: req.body.name,
password: req.body.password,
email: req.body.email,
mobile: req.body.mobile_number
}]
}).save(function(err, doc){
if(err) res.json(err);
else {
res.json({"doc ":doc});
}
})
})
This will create a user object in the user array. Are you sure it's supposed to be an array on not just an object? Remove [] from both the model and controller to make it an ordinary object.
I am new to MongoDb, and I have a question about the insertion of data. My Mongoose schema for 'user' collection:
var user = new mongoose.Schema({
username : {type: String},
email : {type: String,index: {unique: true}},
password : {type: String},
feed : [{
title : {type: String},
description : {type: String},
latitude : {type:Number},
longitude : {type:Number},
feedImages : [{imageUrl: {type: String}}]
}]
});
Here I inserted data to username, email and password in my first service call:
app.post('/users',function(req,res) {
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var userData = {'username':username,'email':email,'password':password};
new db.user(userData).save(function(err,result){
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
});
Then I tried to insert data to feed for the above id.
app.post('/feeds',function(req,res) {
var _id = req.body._id;
var title = req.body.title;
var description = req.body.description;
var latitude = req.body.latitude;
var longitude = req.body.longitude;
db.user.update(
{_id:_id },
{$push : {
feeds:[{
title: title,
description: description,
latitude:latitude,
longitude:longitude
}]
}
}
,function (err,result) {
console.log(err);
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
});
No error is shown, but the data insertion is not happening.
Your latitude and longitude should be converted to numbers:
var latitude = Number(req.body.latitude);
var longitude = Number(req.body.longitude);
I write model for create User and following and followers
var UserSchema = new Schema({
created_at : { type: Date, default: Date.now }
, name : String
, hashedPass : String
, salt: String
, email : Email
, avatar : {type: String, default: "images/default_profile.png" }
, statuses_count : Number
, screen_name : String
, location : String
, about : String
, followers: [{ type: ObjectId, ref: 'Users' }]
, following: [{ type: ObjectId, ref: 'Users' }]
, followers_count : Number
, following_count : Number
});
and in create follow in user I do
UserSchema.statics.createFollowing = function(data, callback) {
console.log("data: ", data);
this.findOne({
name : data.name
}, function(err, docs) {
if (err)
callback("error " + err)
else if (docs) {
docs.following.push({"_id" : data.name_follow});
docs.save(function(err) {
if (err)
callback(err);
console.log("___cxxx_____", this);
mongoose.model('User').findOne({
_id : docs._id
}).populate('following', 'name screen_name avatar').exec(function(err, docs) {
if (err)
callback(err);
console.log('The creator is %s', docs.following)
callback(docs);
});
});
}
});
}
when I request Like this
http://localhost:3000/auth/createfollowing?callback=jQuery16104670869295950979_1361607659796&{"name":"testuser1","name_follow":"envatowebdev","token":"ece20af054339bb52d4feee9a05ab8cc401f8dec6b622b8df1e4c0d1789825bee8dd47f572cdc737a098a5be03044596","device":"xphone"}&_=1361607667778
I return like that
Mongoose: users.findOne({ _id: ObjectId("5128781fcb8c95909c00000e") }) { fields: undefined, safe: undefined }
/data/workspace/node/serverjs/node_modules/mongoose/lib/utils.js:397
throw err;
^
MissingSchemaError: Schema hasn't been registered for model "Users".
Use mongoose.model(name, schema)
at NativeConnection.Connection.model (/data/workspace/node/serverjs/node_modules/mongoose/lib/connection.js:597:11)
at model.populate [as _populate] (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:150:23)
at next (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:269:14)
at next (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:232:57)
at next (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:232:57)
at next (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:232:57)
at next (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:232:57)
at next (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:232:57)
at next (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:232:57)
at init (/data/workspace/node/serverjs/node_modules/mongoose/lib/model.js:215:12)
I don't know why it like that and how to populate following and followers.
Thank in advance
problem is Here model is User but I assigned Users
followers: [{ type: ObjectId, ref: 'Users' }]
For those of you using MEAN.js, #sepdau was correct, but you have to add just one more thing. For example, if you want to create a model that has a field that is an array of Unicorns, this would be the correct syntax:
var StackOverflowSchema = new Schema({
title: {
type: String,
default: 'StackOverflow',
trim: true,
required: 'Name cannot be blank'
},
unicorns: [{ type: Schema.ObjectId, ref: 'Unicorn' }]
});
Im using the following schema and code to create collection in Mongo along with the Indexer and insert data. Please note that the collection is getting created dynamically based on the categoryName.
var employeeSchema = new mongoose.Schema({
categoryId : {type: String, required: true },
loc : {type: {lon: Number, lat: Number}, index: '2d'},
// createdBy : {type: String, required: true },
createDate : {type: Date, default: Date.now}
});
exports.register = function (objEmployee , callback)
{
var emp = db.model(objEmployee.categoryName, employeeSchema );
var objSchema = new emp(objEmployee);
objSchema.save(function (err) {
if (err) return callback(err);
console.info ('Data inserted successfully.');
return callback(null);
});
};
Im able to insert data but when I run the query based on the radious, when I run I get the following error.
Sat Sep 29 20:21:24 uncaught exception: error: {
"$err" : "can't find special index: 2d for: { loc: { $within: { $center: [ [ 50.9393925139, -114.0 ], 2.0 ] } } }",
"code" : 13038
Anything going wrong with in my code ?
I think your schema definition for loc is wrong. It should be
loc: {
lon: Number,
lat: Number
}
And after your schema definition add the index
employeeSchema.index({
loc: "2d"
});