MongoDb Document Not creating discordjs - javascript

I have this code
const usermarket = require('./usermarkets')
const data2 = usermarket.findOne({User:message.author.id})
if(!data2) {
let StonkMarket = new usermarket({
User:message.author.id,
bobloxowned:0,
fattyowned:0,
yeetowned:0,
crunchyrollowned:0,
generatorowned:0,
})
StonkMarket.save().catch(err => console.log(err))
return message.reply('created')
}
But it doesn't create a document in the collection. Here is the usermarket schema code
const userMarket = mongoose.Schema({
User:String,
bobloxowned:Number,
fattyowned:Number,
yeetowned:Number,
crunchyrollowned:Number,
generatorowned:Number,
})
module.exports = mongoose.model("StonkMarketUser", userMarket, 'usermarkets')
It was supposed to create a document with all the things, but instead it did nothing.

Related

Issue with checking and adding document item to collection in MongoDB

I'm new in Nodejs and I'm trying to create Video with hashtag. There are hashtags already storaged in DB, and hashtag that user will create (which will be added when submit video).
For example, I add more than 2 hashtags, the code below works for 2 cases:
If there is no hashtag storaged in DB, it created and add all hashtags to video successfully
If hashtags is already in DB, it added video successfully
But when there are some hashtags already in DB and the other is not. It add only few hashtags to video, not all hashtags added. I don't know why. I want to fix this case.
I have 2 schemas like this:
// Video schema
const videoSchema = new mongoose.Schema({
url: {
type: String
},
hashtag: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Hashtag'
}
})
and
// Hashtag schema
const hashtagSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
}
})
User will POST like this on server. On this example, Tag-In-DB-Already is in DB already and New-Tag is typed by user
{
"url": "https://youtube.com/JvDAQD4",
"hashtag": ["Tag-In-DB-Already", "New-Tag"]
}
videoObj like this
const videoObj = new Video({
url: data.URL,
hashtag: []
})
The checking code like this, I need to push ObjectId (of hashtag) to hashtagArr above. I'm checking for each hashtag, if hashtag not in DB, it will add to DB and then push to array. If hashtag is in DB, it also added to array. I want all hashtags that user submited will be added.
export const addHashtagToVideo = async (hashtagArr, videoObj) => {
await hashtagArr.forEach(hashtagName => { // for each hashtag check
Hashtag.findOne({ name: hashtagName.toLowerCase() }, (err, resp) => {
if (err) return
if (!resp) { // if there is no hashtag in DB
addNewHashtagToDB(hashtagName) // run add new hashtag function
.then(hashtagId => { // newHashtag._id returned from below function
videoObj.hashtag.push({ _id: hashtagId })
})
} else {
videoObj.hashtag.push({ _id: resp._id }) // if found in DB, also pushed to video
}
})
})
}
export const addNewHashtagToDB = async (hashtagName) => {
const newHashtag = await new Hashtag({
name: hashtagName.toLowerCase(),
})
newHashtag.save()
return newHashtag._id
}
Thank you for help
you need to know what is function return...
export const addHashtagToVideo = async (hashtagArr, videoObj) => {
const waitAllDone = hashtagArr.map(async tag => { // tag in hashtagArr
const doc = await addNewHashtagToDB(tag) // find it or create it
return doc.id
})
const ary = await Promise.all(waitAllDone) // [id1, id2]
videoObj.hashtag = ary
// return videoObj
}
export const addNewHashtagToDB = async tag => {
const name = tag.toLowerCase() // whatever tag is, fix it
let doc = await Hashtag.findOne({ name }).exec() // try to find it
if (!doc) {
// not exist
doc = new Hashtag({ name }) // create new doc
await doc.save()
}
return doc
}
another version
export const addHashtagToVideo = async (hashtagArr, videoObj) => {
const waitAllDone = hashtagArr.map(addNewHashtagToDB) // amazing
const ary = await Promise.all(waitAllDone) // [id1, id2]
videoObj.hashtag = ary // replace it to prevent duplicat
// return videoObj
}
export const addNewHashtagToDB = async tag => {
const name = tag.toLowerCase() // whatever tag is, fix it
let doc = await Hashtag.findOne({ name }).exec() // try to find it
if (!doc) {
// not exist
doc = new Hashtag({ name }) // create new doc
await doc.save()
}
return doc.id // return it here
}

Mongoose query for nested schema

I have the following schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProjectSchema = require('./project.js')
const ClientManagerSchema = new Schema({
name : { type : String, required : true},
project : [ProjectSchema]
});
const ClientManager = mongoose.model('clientManager' , ClientManagerSchema);
module.exports = ClientManager;
Inside the clientmanager schema, there is another as you can see. I want to query the database based on a value inside the ProjectSchema.
I am not sure how to do this but I've tried something like:
const find = () => {
ClientManagers.find({ProjectSchema}).then(e => {
console.log(e);
});
}
however, this gives me an empty array.
Easy-peasy you can refer with dot notation:
const result = await ClientManager.find({ 'project.projectName': 'Foo' })

Changes of a json not taken into account NodeJS

I'm coming to you because I'm trying to do a foreach loop on Discord.JS to detect changes in a JSON file. My file does change content, but my foreach loop keeps the old content in memory. I have no idea how to solve the problem...
My index.js:
const Discord = require('discord.js');
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const fetch = require('node-fetch');
const client = new Discord.Client();
const config = require('./config.json');
const database = require('./db.json');
const adapter = new FileSync('./db.json')
const db = low(adapter)
const prefix = config.prefix;
let api = config.api;
client.once('ready', () => {
db.defaults({numbers: []})
.write()
setInterval(function() {
database.numbers.forEach(async element => {
let state = await fetch(`some-api-url`).then(response => response.json());
if(state[0].response != element.response){
db.get('numbers')
.find({number: element.number})
.assign({response: state[0].response, sms: state[0].msg})
.write();
let user = element.clientId;
try {
await client.users.cache.get(user).send(`Your message for number ${element.number} is ${element.sms}`);
} catch(error){
console.log(error)
}
}
});
}, 3000);
console.log('Ready!');
});
It all works, it just keeps the old file in memory.
To solve this problem, I passed my const database = require('./db.json'); into let. Then I integrated fs so that I could clear the cache:
setInterval(function() {
delete require.cache[require.resolve('./db.json')]
database = require('./db.json');
Problem solved!

How can I get the data of another document in the firebase function?

How do I get firestore data in firebase functions?
var number;
await db.collection("users").doc(uid).collection("info").doc("info").get().then(doc => {
number = doc.data().get("countUnMutable").toString;
return db;
});
I want to write the document to a different address using the received value, but it is not written.
exports.changeLocation = functions.region('europe-west1').firestore.document('users/{userId}/firstNotes/{noteId}').onCreate(async (snap,context) => {
const uid = context.params.userId;
const data = snap.data();
const noteId = context.params.noteId;
var number;
await db.collection("users").doc(uid).collection("info").doc("info").get().then(doc => {
number = doc.data().get("countUnMutable").toString;
return db;
});
await db.collection('users').doc(uid).collection("notes").doc("firebaseNote:".concat(number)).set(data);
const alreadyExistedDocument = db.collection('users').doc(uid).collection('notes').doc(noteId);
await alreadyExistedDocument.delete();
});

Iterate Docs on Mongoose

I insert in mongodb with mongoose an array of elements with insertMany function. All goes fine, but I need to take for each element his id. When I insert these elements, i receive an array of docs but i can't iterate them.
Do you have Any solution?
Code example:
const docsExamples = await Examples.insertMany(req.body.examples);
You can use .map() on the array of docs that is returned by insertMany to return a new array of just the ids like this:
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema;
const schema = new Schema({
name: String
});
const Test = mongoose.model('test', schema);
const tests = [];
for (let i = 0; i < 10; i++) {
tests.push(new Test({ name: `test${i}`}));
}
async function run() {
await mongoose.connection.dropDatabase();
const docs = await Test.insertMany(tests);
const ids = docs.map(d => d.id);
console.log(ids);
return mongoose.connection.close();
}
run();
output:
stack: ./49852063.js
[ '5ad47da0f38fec9807754fd3',
'5ad47da0f38fec9807754fd4',
'5ad47da0f38fec9807754fd5',
'5ad47da0f38fec9807754fd6',
'5ad47da0f38fec9807754fd7',
'5ad47da0f38fec9807754fd8',
'5ad47da0f38fec9807754fd9',
'5ad47da0f38fec9807754fda',
'5ad47da0f38fec9807754fdb',
'5ad47da0f38fec9807754fdc' ]
stack:

Categories