not able to save document with ref mongoose - node.js

I can't save my insert
MY MODELS :
Action and Type_intervention
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var actionSchema = new Schema({
action: {
type: String,
required: true,
unique: true
},
}); //Exporter le model
module.exports = mongoose.model('Action', actionSchema);
/*-----------------------------------------*/
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var type_interventionSchema = new Schema({
type_name_intervention : {type : String},
libelle : {type : String},
Standart : {type : String},
libelle_crt : {type : String},
action : {type: Schema.ObjectId, ref: 'Action'},
});
//Exporter le model
module.exports = mongoose.model('Type_intervention',type_interventionSchema);
/*--------------------------------------*/
MY CONTROLLER:
var new_type_intervention = new Type_intervention({
type_name_intervention: req.body.type_name_intervention,
libelle: req.body.libelle,
Standart: req.body.Standart,
libelle_crt: req.body.libelle_crt,
action: req.body.action,
})
new_type_intervention.save((err, newinter) => {
if (err) {
return res.send({
message: 'Error when try to save',
'intervention': new_type_intervention,
'req.action': req.body.action,
'new_type_intervention_action': new_type_intervention.action
});
}
return res.send({
message: 'Add with succes',
'intervention': new_type_intervention
})
})
POSTMAN RUN : The error is catched (new_intervention.action not apear and there type is undefined !? )
I think this is a probleme
{ "type_name_intervention":"f",
"libelle":"f",
"Standart":"f",
"libelle_crt":"f",
"action":"test"}
//Results:
{
"message": "Error when try to save",
"intervention": {
"type_name_intervention": "f",
"libelle": "f",
"Standart": "f",
"libelle_crt": "f",
"_id": "591eb2ccd4325d0e40b2d038"
},
"req.body.action": "test",
"type of new_type_intervention_action": "undefined"
}

I found the solution :
Before save : i try to find the action_id
Action.findOne({
'action': req.body.action,
})
.exec(function (err, found_action) {
if (found_action) {
new_type_intervention.action=found_action._id; // This is GOOD practice
new_type_intervention.save();
return res.send({
'type': typeof req.body.action,
message: 'type intervention ajoutee avec succes '
})
}
})

Related

Auto increment sequence in Mongoose

I am trying to implement Auto increment in uisng mongoose.
But I am stuck.
Counter Schema
counter.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var counterSchema = new Schema({
_id: {type: String, required: true},
sequence_value: {type: Number, default: 1}
});
var Counter = module.exports = mongoose.model('Counter', counterSchema);
Product Schema
products.js
var productsSchema = new Schema({
productId: {type: String, require: false},
merchantId: {type: String, required: false}
)}
I have created counter collection and inserted one record inside it.
{
"_id" : "productId",
"sequence_value" : 1
}
Include method to increment the counter in the counter collection
//COUNTER COLLECTION
function getNextSequenceValue(sequenceName){
var sequenceDocument = Counters.findOneAndUpdate({
query:{_id: sequenceName },
update: {$inc:{sequence_value:1}},
new:true
});
return sequenceDocument.sequence_value;
}
Calling method to increment sequence number:
product.productId = getNextSequenceValue("productid");
But it's not working, nothing is getting saved in the products collection?
the next sequence should be
product.productId = getNextSequenceValue("productId"); // camelCase
in the counter collection you have added document with key productId (camelCase) but trying to get sequence with key productid (all lowercase)
mongo CLI
> function getNextSequenceValue(sequenceName){
...
... var sequenceDocument = db.counters.findOneAndUpdate(
... { "_id" : sequenceName },
... { $inc : { sequence_value : 1 } },
... { new : true }
... );
... return sequenceDocument.sequence_value;
... }
>
EDIT-2 with mongoose
var counterSchema = mongoose.Schema(
{
_id: { type: String, required: true },
sequence_value: { type: Number, default: 1 }
}
);
var Counters = mongoose.model('Counters', counterSchema);
var productsSchema = mongoose.Schema({
productId: {type: String, require: true},
merchantId: {type: String, required: false}
});
productsSchema.pre('save', function(next){
var doc = this;
Counters.findOneAndUpdate(
{ _id: 'productId' },
{ $inc : { sequence_value : 1 } },
{ new : true },
function(err, seq){
if(err) return next(err);
doc.productId = seq.sequence_value;
next();
}
);
}
);
var Product = mongoose.model('Product', productsSchema);
var testProduct = new Product({merchantId : 'test'})
testProduct.save(function (err, doc){
console.log('saved ' + doc )
})
output (with generated productId)
saravana#ubuntu:~/node-mongoose$ node app.js
`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Mongoose: counters.findAndModify({ _id: 'productId' }, [], { '$inc': { sequence_value: 1 } }, { new: true, upsert: false, remove: false, fields: {} })
Mongoose: products.insert({ productId: '36', merchantId: 'test', _id: ObjectId("5a5b27b860716d24007df611"), __v: 0 })
saved { __v: 0,
productId: '36',
merchantId: 'test',
_id: 5a5b27b860716d24007df611 }
^C
saravana#ubuntu:~/node-mongoose$

Is it possible to query subdocuments directly using mongoose?

let's say there was a User model and a Post model. In this situation User's would have many posts; User would be the parent and Post would be the child. Is it possible to query for posts directly?
For instance if I wanted to do something like
app.get('/post/search/:query', (req,res) => {
Posts.find({title: req.params.query }, (err,post) => {
res.send(JSON.stringify(post))
})
})
or would one have to do:
app.get('/post/search/:query',(req,res) => {
let resultsFromQuery = [];
User.find({'post.title':req.params.query'}, (err,user) => {
user.posts.forEach((post) => {
if(post.title === req.params.query){
resultsFromQuery.push(post);
}
})
})
res.send(JSON.stringify(resultsFromQuery))
})
EDIT: Here is my schema's.
User Schema (Parent)
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
PostSchema = require('./post.js');
let UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
posts: [PostSchema]
})
module.exports = mongoose.model('User',UserSchema);
Post Schema (Child)
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
let PostSchema = new Schema({
title: {
type: String
},
description: {
type: String
},
image: {
type: String
},
original_poster: {
id: {
type: String,
required: true
},
username: {
type: String,
required: true
}
},
tags: {
type: [String],
required: true
}
})
module.exports = PostSchema;
EDIT:
Here is a sample document
the result of db.users.find({username: 'john'})
{
"_id" : ObjectId("5a163317bf92864245250cf4"),
"username" : "john",
"password" : "$2a$10$mvE.UNgvBZgOURAv28xyA.UdlJi4Zj9IX.OIiOCdp/HC.Cpkuq.ru",
"posts" : [
{
"_id" : ObjectId("5a17c32d54d6ef4987ea275b"),
"title" : "Dogs are cool",
"description" : "I like huskies",
"image" : "https://media1.giphy.com/media/EvRj5lfd8ctUY/giphy.gif",
"original_poster" : {
"id" : "5a163317bf92864245250cf4",
"username" : "john"
},
"tags" : [
"puppies",
"dogs"
]
}
],
"__v" : 1
}
Yes you can find directly the post title from the user model. like bellow
User.find({"posts.title": "Cats are cool"}, (err, users) => {
if(err) {
// return error
}
return res.send(users)
})
That will return user with all post not only the matching post title. So to return only matching post title can use $ positional operator. like this query
User.find({"posts.title": "Cats are cool"},
{username: 1, "posts.$": 1}, // add that you need to project
(err, users) => {
if(err) {
// return error
}
return res.send(users)
})
that only return matching post
Since you are saving OP data, why not do:
// you'll need to adapt how your are getting the user-id here
const { user } = req
Post.find({ title: 'the title', 'original_poster.id': user.id }, (err, posts) => {
console.log(posts); })
Though I would advise you to adjust your Post-schema:
original_poster: {
type: Schema.Types.ObjectId,
ref: 'User'
}
},
Then you can do Post.find({}).populate('original_poster') to include it in your results.!

Request body unresolved variable Node

I am trying to make a simple registration route using node and express. For some reason the req.body.name is being highlighted as unresolved variable name.
While running in postman it is giving a validation error and saying "Path {PATH} is required."
My javascript code:
router.post('/', function(req, res) {
var participant = new Participant({
name:req.body.name, // this is the place where unresolved variable is coming
regno:req.body.regno,
gender : req.body.gender,
email : req.body.email,
mobile : req.body.mobile,
room : req.body.room,
adgid : req.body.adgid
});
participant.save(function(err,docs) {
if(docs) {
res.json({
"message":docs
})
}
else{
res.json({
code: '1',
message: err
})
}
});
My model file:
var mongoose = require('mongoose');
var participantSchema = mongoose.Schema({
name:{ type: String , required :true},
regno:{ type:String, required :true },
gender:{ type:String, required :true },
mobile:{ type: Number ,required :true },
email:{ type:String,required :true },
room:{ type:String ,required :true },
adgid : {type:String , required : true}
});
var Participant = mongoose.model('Participant', participantSchema);
module.exports= {Participant : Participant};

MongoDB insertion not working

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);

Mongoose doesn't create model object with array

I'm working on a project where I have the following mongoose schema:
module.exports = mongoose.model('Env', {
name : {type : String, default: ''},
services: [ServiceAddress]
});
module.exports = mongoose.model('ServiceAddress', {
serviceId : {type : ObjectId},
address: {type: String}
});
I'm trying to update an existing 'Env' document which has an empty array of 'services'.
router.put('/api/env', function(req, res, next) {
var env = new Environment(req.body);
env.save(function(err, updated){
if (err){
res.send(err);
}
res.json(updated);
});
});
The req.body content is:
{
_id: "56dd26a6618c1b983d5bada6",
name: "Test Drive"
services: [{_id: "56dc6e385fb0b038241d3399", address: "11"}, {_id: "56dc6e595fb0b038241d339a", address: ""}]
}
But the result in the DB is (only the IDs are pushed):
"services" : [ { "_id" : ObjectId("56dc6e385fb0b038241d3399") }, { "_id" : ObjectId("56dc6e595fb0b038241d339a") }
Any idea?
Thanks
Please try out with following snippet
var serviceSchema = {
serviceId : {type : ObjectId,required: false},
address: {type: String,required: false}
};
// added so that new _id field is not added when object is pushed in array
serviceSchema = 'new Schema('+serviceSchema +',{_id:false})';
module.exports = mongoose.model('Env', {
name : {type : String, default: ''},
services: [serviceSchema], default:[],
});
Thanks

Resources