node, mongoose 'findOne' on one collection inside 'find' of another collection
Date : March 29 2020, 07:55 AM
will be helpful for those in need findOne is async so the callbacks for both owners' findOne result can be queued up to run where user.some_field for both have the same initial value. Each callback then runs and saves the new value as the initial value plus 1. This is the classic case for why you want to use an update with the atomic $inc operator instead. UserModel.findOneAndUpdate({username: car.owner}, {$inc: {some_field: 1}},
function(err, numAffected) { ... }
);
|
Mongoose fetch documents from another collection which has current collection's document as reference
Tag : node.js , By : vitorcoliveira
Date : March 29 2020, 07:55 AM
it fixes the issue If you are actually asking that you want the "relation" to be done the "other way around" then the anwser is to "store" that relation in that way in the first place. Therefore: var bookSchema = new Schema({
title: { type: String },
author: { type: Schema.Types.ObjectId }
});
Books.find({ "author": authorId })
.populate("author")
.exec(function(err,books) {
// stuff in here
});
Books.find().execute(function(err,books) {
var results = [];
async.each(books,function(book,callback) {
Author.findOne({ "books": book._id },function(err,author) {
var obj = book.toObject();
book.author = author;
results.push(books);
callback(err);
});
},
function(err) {
if (err) throw err;
console.dir(results);
});
})
|
Collection isn't being saved in mongodb (Story collection from the mongoose populate documentation)
Date : March 29 2020, 07:55 AM
I wish did fix the issue. The below code gives me this error: , I think this would do the trick. var express = require("express");
var app = express();
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
mongoose.connect("mongodb://localhost/pop2");
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{type : Schema.Types.ObjectId, ref : "Story"}]
})
var storySchema = Schema({
_creator : {type : Number, ref : "Person"},
title : String,
fans : [{type : Number, ref : "Person"}]
});
var Story = mongoose.model("Story", storySchema);
var Person = mongoose.model("Person", personSchema);
var aaron = new Person({_id : 0, name :"Aaron", age : 100});
aaron.save(function(err){
if(err) return handleError(err)
});
var story1 = new Story({
title : "Once upon a timex.",
_creator : aaron._id
});
story1.save(function(err){
if(err) return handleError(err);
console.log("saved")
});
Story.findOne({title : "Once upon a timex."})
.populate("_creator")
.exec(function(err, story){
console.log(story);
if(err) return handleError(err);
console.log("The creator is %s", story._creator.name)})
app.listen(3000, function(){
console.log("listening on 3000")
});
|
Not able to perform operation with mongoose on db collection with few conditions
Date : March 29 2020, 07:55 AM
will be helpful for those in need I have used promise library but you can also use callbacks Assumption : You want to work on User model User.findOne({username:"USERNAME"}).exec()
.then((result)=>{
if(result){
if(result.id == 1){
//update result object and then save it
result.lastName="abc";
result.save(); // it will update your result
}else{
console.log('failed to enter in the db.')
}
}else{
User(userObject).save(); // it will create new entry
}
})
|
Mongodb or mongoose fetch all records from collection A into other aggregate query which is fetching B collection data
Date : March 29 2020, 07:55 AM
like below fixes the issue I don't think you can, and neither you should. Getting all records of some collection is bad practice, always try to limit yourself with only things you need. If you really want to add resutls from some totally unrelated collection then you should make separate request and then add them together in json you sending to client.
|