Mongoose save parent model with child model - javascript

How to save une ligne de stations? I have 2 shemas models station et. The method that I make doesn't work for me. see the pictures.

var LigneSchema = mongoose.Schema({
titre: String,
stations: [{ type: Schema.Types.ObjectId, ref: 'Station' }],
});
var StationSchema = mongoose.Schema({
titre: String,
lieu: String,
depart : boolean ,
arrive : boolean,
lignes: [{ type: Schema.Types.ObjectId, ref: 'Ligne' }]
});
var ligne = new Ligne({titre : req.body.titre, stations: []}) ;
ligne.save(function(err, data) {
console.log(data);
if(err) {
console.log(err);
res.status(500).send({message: "Une erreur s'est produite lors de la création du bus."});
} else {
res.send(data);
}
});
};

Related

findByIdAndUpdate pull from array objects equal to a specific value

I want to remove one or more objects of type tweet from the timeline list within the user model. The tweet objects that I want to remove are those whose author id matches a specific id user._id.
I have tried this:
router.get("/follow/:userId", isLoggedIn, catchAsync(async (req, res) => {
try {
const currentUser = await User.findById(req.user._id).populate("timeline")
const user = await User.findById(req.params.userId).populate("followers tweets")
for (let tweet of currentUser.timeline) {
if (tweet.author._id.equals(user._id)) {
currentUser.timeline.pull(tweet._id)
}
}
req.flash("error", `Unfollowed to ${user.username}`)
user.save();
currentUser.save()
res.redirect(`/${user._id}`)
} catch (err) {
req.flash("error", err.message);
res.redirect("back")
}
}));
and this:
await User.findbyIdAndUpdate(currentuser._id, { $pull: { timeline: { author : user._id } } }
but none of them are working.
My user model:
const userSchema = new Schema({
name: {
type: String,
required: true
},
biography: { type: String, maxlength: 160 },
location: {type: String, maxlength: 30 },
email: {
type: String,
unique: true,
required: true
},
image: {
url: String,
filename: String,
},
followers: [{ type: Schema.Types.ObjectId, ref: "User" }],
following: [{ type: Schema.Types.ObjectId, ref: "User" }],
tweets: [{ type: Schema.Types.ObjectId, ref: "Tweet"}],
timeline: [{ type: Schema.Types.ObjectId, ref: "Tweet"}]
});
My tweet model :
const tweetSchema = new Schema({
images: [{
url: String,
filename : String
}],
text: { type: String, maxlength: 260},
date: { type: Date, default: Date.now },
author: { type: Schema.Types.ObjectId, ref: "User" },
parent: { type: Schema.Types.ObjectId, ref: "Tweet", default:null },
replies: [{ type: Schema.Types.ObjectId, ref: "Tweet" }],
likes: [{ type: Schema.Types.ObjectId, ref: "User" }],
retweets: [{ type: Schema.Types.ObjectId, ref: "Tweet" }],
retweetStatus: {type: Schema.Types.ObjectId, ref: "Tweet", default: null}
});
If your collection looks like this:
[
{
"_id" : ObjectId("60254276259a60228cbe5707"),
"name" : "Mary",
"timeline" : [
ObjectId("60254276259a60228cbe5703"),
ObjectId("60254276259a60228cbe5704"),
ObjectId("60254276259a60228cbe5705")
]
},
{
"_id" : ObjectId("60254276259a60228cbe5706"),
"name" : "Dheemanth",
"timeline" : [
ObjectId("60254276259a60228cbe5700"),
ObjectId("60254276259a60228cbe5701"),
ObjectId("60254276259a60228cbe5702")
]
}
]
then the solution is:
usersSchema.updateOne(
{
"_id": ObjectId("60254276259a60228cbe5706"),
"timeline": ObjectId("60254276259a60228cbe5700"),
},
{
$pull: {
"timeline": ObjectId("60254276259a60228cbe5700")
}
}
)
.then()
.catch()
// or
usersSchema.findOneAndUpdate(
{
"_id": ObjectId("60254276259a60228cbe5706"),
"timeline": ObjectId("60254276259a60228cbe5700"),
},
{
$pull: {
"timeline": ObjectId("60254276259a60228cbe5700")
}
},
{
new: true
}
)
.then()
.catch()
I finally found the issue! The problem I was having is that I was trying to remove items from a list of objects while looping through that list. The solution is easy: you can just create an auxiliar empty array and push the items that you want to remove, then loop through that auxiliar array and pull the items from the original array.
In my case, I've already had an array with the tweets that I wanted to remove, user.tweets. The solution is:
router.get("/follow/:userId", isLoggedIn, catchAsync(async (req, res) => {
try {
const currentUser = await User.findById(req.user._id).populate("timeline")
const user = await User.findById(req.params.userId).populate("followers tweets")
for (let tweet of user.tweets) {
currentUser.timeline.pull(tweet._id)
}
req.flash("error", `Unfollowed to ${user.username}`)
user.save();
currentUser.save()
res.redirect(`/${user._id}`)
} catch (err) {
req.flash("error", err.message);
res.redirect("back")
}
}));

How to edit an Embed Author?

I want to edit the author of an embed sent by my bot.
The message is sent by this code :
task_chan.send('', {
embed: {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
})
To edit the message I've tried :
taken.embeds[0].author.icon_url = util.avatarURL
taken.embeds[0].author.name = util.username
taken.edit(new Discord.RichEmbed(taken.embeds[0]));
taken contain the message to edit and util an user.
And it only change the name…
I don't understand why but author.icon_url is undefined between these two code samples.
I hope you can help me :)
method channel.send return a promise, so you can use .then(msg=> to get a message object.
let testEmbed = {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
}
task_chan.send({embed:testEmbed}).then(msg => {
testEmbed.name = 'LOL'
testEmbed.iconURL = 'SOMEURL'
msg.edit({embed:testEmbed})
})
I would recommend that you use the built-in methods for creating embeds, in my opinion it is more convenient.

How to update an object inside an array inside an object with mongoose?

Let's say I want to update "numberOfUpVotes" where the title is "Een centrale plek voor alle ideeen". I want the new value of "numberOfUpVotes" to be stored in the database. How do I do that?
Right now my code doesn't give an error, but it also doesn't work. This is what I've tried:
Board.findOneAndUpdate(
{"ideas.numberOfUpVotes": 23},
{$set: {"numberOfUpVotes": 2}}, // $set
{new: true},
function (err, doc) {
if (err) return res.send(500, {error: err});
console.log("hallo");
});
This is my data:
{
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
{
_id: ida1,
userId: id1,
title: 'Een centrale plek voor alle ideeen',
text: 'Een plek waar alle ideeen getoond worden op een scherm ofzo. Waar mensen dan op kunnnen stemmen via hun telefoon',
date: new Date('2019-04-12'),
numberOfUpVotes: 23,
},
{
_id: ida2,
userId: id1,
title: 'Een uber voor kerstbomen',
text: 'Bestaat zoiets al?',
date: new Date('2019-04-11'),
numberOfUpVotes: 1,
}
],
QRcode: 'Dit is een QRcode'
}
You can do this without mongoose, something like.
const board = {
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
{
_id: 'ida1 (demo)',
userId: 'id1 (demo)',
title: 'Een centrale plek voor alle ideeen',
text: 'Verkort voor demonstratie',
date: new Date('2019-04-12'),
numberOfUpVotes: 23,
},
{
_id: 'ida2 (demo)',
userId: 'id1 (demo)',
title: 'Een uber voor kerstbomen',
text: 'Bestaat zoiets al?',
date: new Date('2019-04-11'),
numberOfUpVotes: 1,
}
],
QRcode: 'Dit is een QRcode'
};
// find the filtered record and update its value
// the found record is a reference, so the value
// is indeed changed within the object
board.ideas.filter(idea => idea.numberOfUpVotes === 23).shift().numberOfUpVotes = 2;
// QED
console.log(JSON.stringify(board, null, " "));
This is my final answer:
Board.update(
{"ideas._id": mongoose.Types.ObjectId("abc123")},
{$inc:{"ideas.$.numberOfUpVotes": 1}},
function (err, doc) {
if (err) return res.send(500, {error: err});
console.log("succes! (:");
})

node.js how to find a document inside Inner Mongodb

Please teach me how to find a document inside Inner Mongodb. I'd like to bring you some coordinates inside the market. What should I do?
/**
* 데이터베이스 스키마를 정의하는 모듈
*
* #date 2016-11-10
* #author Mike
*/
//var crypto = require('crypto');
var Schema = {};
Schema.createSchema = function(mongoose) {
// 스키마 정의
var ItemSchema = mongoose.Schema({
itemName : {type: String, index: 'hashed', 'default':''}
,market : {
marketName: {type: String, index: 'hashed', 'default':''}
, marketId: {type: String, required: true, 'default':''} //마켓 고유번호
, geometry: {
type: {type:String, default:'Point'},
coordinates: [{type:'Number'}]
}
, tel: {type: String, required: true, 'default':''}
, address: { data: Buffer, contentType: String,default:'' }
}
,price : { type: 'Number',default:''}
,disPrice: {type: 'Number',default:''}
,count: {type: 'Number',default:''}
,expireTime : {type: Date, index: {unique: false} }
});
console.log('ItemSchema 정의함.');
ItemSchema.index({geometry:'2dsphere'});
ItemSchema.static('findNear',function(longitude,latitude,maxDistance,callback){
console.log('findNear 호출됨')
this.find().where('geometry').near({
center:{
type:'Point',
coordinates:[parseFloat(longitude),parseFloat(latitude)]
},
maxDistance:maxDistance
}).exec(callback);
});
return ItemSchema;
};
// module.exports에 UserSchema 객체 직접 할당
module.exports = Schema;
this is router
var findNearItem = function(req, res) {
console.log(' findNearData.');
var paramLongitude = req.body.longitude || req.query.longitude;
var paramLatitude = req.body.latitude || req.query.latitude;
var maxDistance = 10000;
var database = req.app.get('database');
database.ItemModel.findNear(paramLongitude, paramLatitude, maxDistance, function(err, results) {
if(err) {
console.dir(err);
return;
}
console.log('결과 -> ' + JSON.stringify(results));
var context = {
results:results
};
var output = JSON.stringify(context);
res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
res.write(output);
res.end();
});
};
this is config
{file:'./item',path:'/process/findNearItem',method:'findNearItem',type:'post'}
The find query return the whole record document, even if the query condition checking on an attribute in the sub document of the record like coordinates but in your case you want to return just the coordinates sub document.
I suggest using aggregate.
this.aggregate(
[{
$group: {
_id:"$market.geometry.coordinates"
}
}])
If you want to have the max value of coordinates in a maxDistance field
db.getCollection('market').aggregate(
[{
$group: {
_id:"$market.geometry.coordinates"
}},{
$project: { maxDistance: { $max: "$_id" }} //_id here is refering to "market.geometry.coordinates"
}])
Pipeline builder technique within schema static method:
ItemSchema.static('findNear',function(longitude,latitude,maxDistance,callback){
console.log('findNear 호출됨');
return this.aggregate().group({
_id:"$market.geometry.coordinates"
}).project({
maxDistance: { $max: "$_id" }
}).exec(callback);
});
sorry I can't use aggregate, I solved the problem by modifying the ItemSchema .
var ItemSchema = mongoose.Schema({
itemName : {type: String, index: 'hashed', 'default':''}
, marketName: {type: String, index: 'hashed', 'default':''}
, marketId: {type: String, required: true, 'default':''} //마켓 고유번호
, geometry: {
type: {type:String, default:'Point'},
coordinates: [{type:'Number'}]
}
, tel: {type: String, required: true, 'default':''}
, address: { data: Buffer, contentType: String,default:'' }
,price : { type: 'Number',default:''}
,disPrice: {type: 'Number',default:''}
,count: {type: 'Number',default:''}
,expireTime : {type: Date, index: {unique: false} }
});

Query mongoose -- Finding all battle where opponet id equals or challanger id equals some_id

I trying to query my mongo db for all battles a player has played. I was wondering about the or operation in mongoose. I can't get it to work.
I have tried something like this:
var currentUser = req.params.player_id;
Battle.find({}).populate({
path: 'utfordrer motstander',
}).where('utfordrer.id').equals(currentUser).$or('motstander.id').equals(currentUser).exec(function (err, battle) {
if (err){
console.log(err);
}
else {
console.log(battle);
}
});
This is my battle schema:
var battleSchema = new mongoose.Schema({
utfordrer: {
id: {type: mongoose.Schema.Types.ObjectId, ref: "User"},
username: String,
score: Number,
ferdig: Boolean
},
motstander: {
id: {type: mongoose.Schema.Types.ObjectId, ref: "User"},
username: String,
score: Number,
ferdig: Boolean
},
spill:
{
id: {type: mongoose.Schema.Types.ObjectId, ref: "Game"},
navn: String,
beskrivelse: String
},
tidspunkt: Date
});
Battle.find({$or:[ {'utfordrer.id': currentUser}, {'motstander.id': currentUser}]}).exec(function (err, battle) {
if (err){
console.log(err);
}else{
console.log("===========UTFORDRINGER");
console.log(battle.length);
res.render("Battles/index", {antallUtfordringer: antall, battleId: utfordringBattleId});
}
});

Categories

Resources