Proper way to check a property of Mongoose Document is empty - node.js

Suppose a schema
const sch = new mongoose.Schema({
obj: {
subObj: String;
}
});
Then I observe that an non-existing or empty property of a document gives me isEmpty == false.
import { isEmpty } from 'lodash';
// Insert an empty document (i.e. no `obj` property)
Sch.create([{}]);
Sch.findOne({}. (err, doc) => {
// Below gives `{}`
console.log(doc.obj);
// Below gives `false`
console.log(`isEmpty == ${isEmpty(doc.obj)`);
});
I suspect that it is because the document contains obj as its key, i.e. Object.keys(doc).includes('obj') == true or Object.getOwnPropertyNames(doc).includes('obj') == true. But I have no idea to deal with it.
What is a proper way to check emptiness of a mongoose document property ?

Update:
The reason that you are getting that is:
console.log(Object.keys(doc.obj), Object.keys({}));
when running the command above I get: [ '$init', 'subObj' ] [] which means that your Object is not really empty, lodash is probably checking those attributes
You could use something like this:
Sch.findOne({}, (err, doc) => {
if (JSON.stringify(doc.obj) === JSON.stringify({}) ) {
// logic goes here
}
});

I found the solution in mongoose itself. The below does what I tried with lodash
doc.$isEmpty('obj')
Reference
Document.prototype.$isEmpty()

Related

Node.js & MongoDB not reading variable correctly

Recently, I changed key of object in MongoDB.
{
links: {
changed: 'value',
notchanged: 'value'
}
}
This is what I get from my MongoDB collection. Data which key is not changed is still readable by links.notchanged but data which key is changed like links.changed is not readable and only outputs undefined. Node.js gets and reads the whole links data correctly but when it comes to links.changed it doesn't. How do I solve this problem? Code below:
scheme.findOne({}, (err, data) => {
if (err) res.send('ERR')
else {
console.log(data) // prints full data, same as JSON above
console.log(data.links.changed) // undefined
}
}
You are matching {class:'210'}.. Is it available in document. Probably Your query returns empty object in data . Confirm the match query... Otherwise your code seems ok.
await db1.findOne({class: "210"}, (err, data) => {
console.log(data.links.changed) // returns value
})
Or Try the code like this
await db1.find({ class: "210" }).toArray()
.then(data => {
console.log(data[0].links.changed) //"value"
});
You should make a variable instead of an object for this. For example: Use changed and assign it value as true or false

Mongoose get updated document after instance.update()

I am executing a mongoose Model.findById() function in order to return a single instance by utilizing an express route.
Model.findById(modelid)
.then(instance => {
if(instance.isOwnedBy(user)) {
return instance.update({$push: {days: req.params.dayid}}, {new: true})
.then(foo => res.send(foo))
} else {
res.status(401).send("Unauthorized")
}
})
the above code returns an object containing the opTime, electionId...etc instead of returning the newly updated document instance. How am I able return the newly updated document after the instance.update() method?
If instance.isOwnedBy(user) and _id: modelid can be merged into one mongo query, it's better to use findOneAndUpdate() but in that way, if it doesn't find any document match, you can not know which part of the query causes the not found.
And because I don't know much about your models, conditions, I can not answer how to do it with findOneAndUpdate() but there is another way that modify the document and call save() method.
Example base on your code:
Model.findById(modelid)
.then(instance => {
if(instance && instance.isOwnedBy(user)) {
if(instance.days) instance.days.push(req.params.dayid);
else instance.days = [req.params.dayid];
instance.save().then(function(instance){
res.send(instance);
})
} else {
res.status(401).send("Unauthorized")
}
})
Note: You should check if the instance exist or not before modify it.

CoreMongooseArray to Normal Array

I'm shortlisting the 2 elements from one schema and want to update in another schema. for that i used slice method to shortlist first 2 elements from an array. but am Getting
CoreMongooseArray ['element1','element2']
instead of ["element1", "element2"]
How do i remove "CoreMongooseArray" ?
connection.connectedusers.find({}, async (err, docs) => {
if(err) throw err;
var users = docs[0].connectArray;
if (docs[0] != null && users.length >= 2) {
var shortListed = users.slice(0, 2);
try {
await connection.chatschema.updateMany({}, { $push: { usersConnected: [shortListed] } }, { upsert: true });
} catch (err) {
res.status(201).json(err);
}
}
You need to add lean() to your query.
From the docs:
Documents returned from queries with the lean option enabled are plain javascript objects, not Mongoose Documents. They have no save method, getters/setters, virtuals, or other Mongoose features.
If you already got the mongoose array and like to convert to simple js array
const jsArray = mongooseArray.toObject();
https://mongoosejs.com/docs/api/array.html#mongoosearray_MongooseArray-toObject
For some reason .toObject() didn't work for me. lean() option works, but it's not suitable when you already have an object with mongoose array in it. So in case if you already have mongoose array and you want just to convert it to plain js array you can use following code:
function mongooseArrayToArray(mongooseArray) {
const array = [];
for (let i = 0; i < mongooseArray.length; i += 1) {
array.push(mongooseArray[0]);
}
return array;
};
usage:
const array = mongooseArrayToArray(mongooseArray);
If you just want to convert the CoreMongooseArray to a normal array without changing anything else:
const jsArray = [...mongooseArray];

findOneAndUpdate with Upsert always inserting a new user

I want to do is update a record and insert it if it doesn't exist with mongoose. Here is my code:
module.exports.upsertUser = function(user) {
var options = {userName : 'Ricardo'}
Users.findOneAndUpdate({email: user.email}, options, {upsert:true}).exec();
}
And:
var promise = Users.upsertUser(user);
promise
.then(function(results){
...
}
.catch(function(err){
...
}
When I execute the promise, each time a new user is created with the same email.
I'm not sure if I'm performing the update incorrectly. I've tried it in the same way but with update and it does not work either.
Can you help me? Thanks!
You need to put the return without the exec:
module.exports.upsertUser = function(user) {
var options = {userName : 'Ricardo'}
return Users.findOneAndUpdate({email: user.email}, options, {upsert:true, new: true});
}
var promise = Users.upsertUser(user);
promise.then(function(results){
if(results) {
console.log(results);
} else {
console.log('!results');
}
}.catch(function(err){
...
}
FYI:
The default is to return the unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: {new:true} with the upsert option.
according to your coding what findOneAndUpdate() does is that it finds this document/user's document that you are looking for to edit which in this case what you are using to search for this user's document that you want to edit it's document is with his email. Now your second argument modifies that part of the document that you wanted to modify, but this option has to be attached with some mongodb operators (pay a visit to this link for a list of them: https://docs.mongodb.com/manual/reference/operator/update/) but in your case what you need is the $set operator.so i would modify your code like this:
module.exports.upsertUser = function(user) {
var options =
Users.findOneAndUpdate({email: user.email}, {$set:{
userName : 'Ricardo'
}}, {
returnOriginal: true}).exec();
};
so try the above modification let's see how it works

How to return data as JSON in Sequelize

When I make a Sequelize query it returns to me an object (or array) which I'm guessing is a Sequelize model (or array of Models (a collection type??)) but it's not documented anywhere, so I'm just guessing. I would always like the results to be JSON. Is there anything I can pass in the query to force this? I would prefer not to hand massage every result I get back to be JSON if possible.
The documentation show this to return a string:
console.log(JSON.stringify(users))
So there's some built in serialization. Right now I'm doing this, using the undocumented toJSON() method:
query().then(function(result) {
if(result.length) {
return result.toJSON();
} else {
return result.map(function(item) {
return item.toJSON();
});
}
});
which is cumbersome.
You can use raw: true in the Query however this does not always behave as you might expect, especially with associations.
query({
// ...
raw: true
}).then(function(result) {
// Result is JSON!
});
However in the case where you're using associations you may get something like this:
{
foo: true,
"associated.bar": true
}
Instead of what you might expect:
{
foo: true,
associated: {
bar: true
}
}
When you retrieve the model from the database, you can call the .get({ plain: true}) on the result and it will handle the conversion for you. You can assign the value of the function call to a variable. For example
..).then(function(user){
var _user = user.get({ plain: true});
console.log(_user); //Should be valid json object
});
Hope this helps.
If you're doing a query with which has multiple results you should expect an array to be returned. You should find that each element in the result array is a JSON object.
You should be able to access a given field like this: result[0].myfieldname

Resources