I Have an array of String which I want to save in Mongodb in Node/express, it is saving Empty array in Mongodb
const multiImagesSchema = mongoose.Schema({
names:Array
})
import ImgArray from '../../Model/multiImages.js'
let imgNames = req.files.map(imgName=>{
return imgName.originalname
})
// console,log(imgNames)
//result in console: ['Apple,png', 'Grapes.png','Ornage.png','Banana.png']
const imageArray = new ImgArray(imgNames)
await imageArray.save()
You have to pass the object with properties defined in schema Model to the creation function (in your case the object with names property). You are passing the imgNames array. Change you code like this:
await ImgArray.create({ names: imgNames });
your model need to have a field that accepts array like this:
const ImgArraySchema = mongoose.Schema({
names: [{
type: String,
required: true
}]
})
then to save an array, do it like this:
const imageArray = new ImgArray({names: imgNames})
const imgarray = await imageArray.save()
.catch((err) => (res.status(500).send({err: err.message})))
if (imgarray) {
return res.status(200).send({success: true, imgarray})
}
return res.status(400).send({success: false, error: ""})
Related
I'm trying to delete an object inside an array in my DB using the $pull in Mongoose but does not work.
This is my attempt:
const listSchema = new Schema({
name: String,
items: []
});
const List = mongoose.model("list", listSchema);
const itemDeleted = req.body.checkbox;
//I get here the ID of the object inside the array
const itemListDeleted = req.body.listDeleted;
// Here the name of the object that contains the array
List.findOneAndUpdate({name:itemListDeleted},{$pull:{items:{_id: itemDeleted}}},function (err,foundList) {
if (foundList){
res.redirect("/"+ itemListDeleted);
} else {
console.log(err);
}
})
I searched for solutions and everybody recommends using $Pull but in my case, it doesn't work. I log the const and all things appear to be right.
Do you have any suggestions?
I'm trying to create a document in my Schema that essentially works like a dictionary with an array of values (dates):
I want to use this to keep track of email correspondence I am sending users:
let d = {
'generic-contact' = ['11/02/2019', '11/05/2020'],
'update-profile' = ['1/01/2018']
}
I would then update this document field with something like:
let emailAddresses = ['joebloggs#yahoo.com', 'foobar#googlemail.com']
let recipients = await Profile.find({ email: { "$in" : emailAddresses } })
let emailTopic = 'newsletter03'
recipients.forEach(user => {
user.correspondenceHistory[emailTopic].push(Date.now())
user.save()
})
I want to do this so that I make sure that I don't send the same user the same email within a certain period of time.
However I can't work out how to set this up in my schema. Is this sort of structure possible?
I've tried many different structures for correspondenceHistory, but none of them have worked and I can't work out what I'm doing wrong. Here is my schema as it stands:
const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
var profileSchema = new mongoose.Schema({
email: String,
firstname: String,
lastname: String,
correspondenceHistory: { type: Array } ### Here ###
}, { discriminatorKey: 'accountType', retainKeyOrder: true, timestamps: true });
I'm getting a list of objects as a response like this
As you can see the objects are not in an array. I want to push these objects into an array. I tried the following way
this.setState({
countrydata: this.state.countrydata.push(datasnapshot.val()),
})
But it didn't work. What's the correct approach to push these objects into an array?
PS:
componentDidMount() {
const countryCode = this.props.match.params.countryCode;
var countryName = getName(countryCode);
var firebaseHeadingref = firebase.database().ref(countryCode);
firebaseHeadingref.once('value').then(datasnapshot => {
this.setState({
countrydata: datasnapshot.val(),
countryName: countryName,
loading: false
})
});
}
I think that the "countrydata" in a dict not an array.
Try to initialize the it as an empty array.
Array.prototype.push returns the new length of the array after the push, so you are essentially setting the state to a number.
You are not allowed to mutate the array with React state, you need to create a new array containing your new elements:
// When updating state based on current state, use the function form of setState.
this.setState(state => {
countrydata: [...state.countrydata, datasnapshot.val()],
})
This is assuming countryData is indeed an array, which from your screenshot, it appears to not (it seems to be an object), so you may be set something wrong somewhere along the way (or datasnapshot.val()) doesn't contain what you think it contains.
You could do this:
const keys = Object.keys(countryData); // array of the keys ["place_1", ...]
const array = Array(keys.length); // Prepares the output array of the right size
for (let i=0; i<keys.length; i++) {
const country = countryData[keys[i]]; // get the next country object
country.key = keys[i]; // add the key into the object if you need it
array[i] = country; // store the value into the array at index 'i'
}
// array now is [ {key: "place_1", description: "Sigiriya Rock Fortress"}, ...]
this.setState({countryDataArray: array});
You could try something like this. Array.prototype.push().
I have not tested below code.
componentDidMount=async() =>{
const countryCode = this.props.match.params.countryCode;
var countryName = getName(countryCode);
var firebaseHeadingref = firebase.database().ref(countryCode);
const datasnapshot = await firebaseHeadingref.once('value');
this.setState(prevState=>{
...prevState,
countryName,
countrydata: [...prevState.countrydata, datasnapshot.val()],
loading: false,
},()=>console.log("done!"))
}
You need to convert the response data from firebase to an array like this:
componentDidMount() {
const countryCode = this.props.match.params.countryCode;
var countryName = getName(countryCode);
var firebaseHeadingref = firebase.database().ref(countryCode);
firebaseHeadingref.once('value').then(datasnapshot => {
const countryData = datasnapshot.val();
const countryDataArray = [];
for (const key in countryData) {
countryDataArray.push({ key, ...countryData[key]});
}
this.setState({
countrydata: countryDataArray,
countryName: countryName,
loading: false
})
});
}
Use for-in to loop through the object or use Object.keys().
const data = datasnapshot.val();
const countrydata = [];
for (let key in data) {
countrydata.push(data[key])
}
// using Object.keys()
Object.keys(data).forEach((key) => countrydata.push({ [key]: data[key]}))
this.setState({
countrydata
})
const data = {
place1: { name: 'One'},
place2: { name: 'Two'},
place3: { name: 'Three'},
};
const countrydata = [];
for (let key in data) {
countrydata.push({ [key]: data[key] });
}
console.log(countrydata);
I want to access the content of array of document in my model, but I can't and return undefined.
here is my model(Project.js):
var mongoose = require('moongoose');
var Schema = mongoose.Schema;
var User = require("./Users");
var ProjectSchema = new Schema({
name: String,
description: String,
owner: {
type: mongoose.SchemaTypes.ObjectId,
ref: "User"
},
contributor: [{
type: mongoose.SchemaTypes.ObjectId,
ref: "User"
}]
});
module.exports = mongoose.model('Project', ProjectSchema);
and my Api:
var Project = require('./Project')
await Project.find({owner: userId, name: name})
.then(project => {
console.log(project);
console.log(project.contributor);
}).catch(err => {
res.status(500).send({
message: err.message
});
});
when i try console.log(project); return expected output but in console.log(project.contributor); return undefined
I've also searched the web but couldn't find anything right and clear solution
I appreciate any help :)
As you are expecting to find only one project, change find by findOne method. Other case you are searching for several projects and you are going to receive an array instead of an object.
Your output from Project.find() (See) will be an array of objects from the database.
If you will only have 1 object as a result then you can use project[0].contributor because project is an array with 1 object inside it, which is on the index 0.
If the result might have many objects in the array then you should iterate through the result to get each of the data individually.
project.forEach(p => console.log(p.contributor))
I am trying to add a new key:value pair to an existing object of mongoDB document, but no steps are helping me
I tried $each, $push $addtoset but i understood those are for arrays then i tried $det but it is updating the existing key:value pair with new key:value pair
Here is my document
{
test:"abc",
test2:"cdf",
test3:{ 1:"one"}
}
if you observer test3 key in the above document i have already 1:"one" now i want to add new key value in the same object
Like
{
test:"abc",
test2:"cdf",
test3:{ 1:"one", 2:"two", 3:"three"}
}
is it possible in mongoDB?
Here is the mongo Query
let val = parseInt(DYNAMICVALUE)
var changfeemaildot = (req.session.email).replace(/\./g, '#')
var seld = {
_id: ObjectId(rx[0]._id)
};
var seldu = {
$set:{
emails: {
[changfeemaildot]: val
}
}
};
var collection =
connection.get().collection('problems');
collection.update(seld, seldu, function (err, rail) {
});
You can use $set. So your code can be something like this
db.collection.update({<your_condition>}, {$set: {"test3.2": "two", "test3.3": "three"}});
In your case, it will be something like this
var seldu = {$set: {["emails." + changfeemaildot]: val}}
You can use $set with findOneAndUpdate. So your code can be something like this
const { Types, connection } = require("mongoose");
const productList = await connection.collection('products').find({}).toArray()
productList.forEach(async function(myDoc) {
await connection.collection('products').
updateOne({ productId: Types.ObjectId(myDoc.productId) }, {
$set: {
productDisplayId: 'anything you want'
}
});
});