Insert document with nested ObjectId - node.js

I am trying to insert a document into my mongodb that looks like this:
_id : ObjectId(<id>)
players : {
ObjectId(<id>) {
entry : 'foo'
}
}
However, I can't form JSON in node with an ObjectId as a key. What's the best practice for this? Thanks!

According to the MongoDB documentation:
Field names are strings.
So you can't use ObjectId's as keys, but you can use their string representation:
var playersObj = {};
playersObj[ObjectId()] = { entry : 'foo' }; // this will stringify the ObjectId
var document = {
_id : ObjectId(),
players : playersObj
};

Related

FindOne by index in mongoose

I have a mongoose collection that store specific data. and I have an iduser. that's name : var members = new Schema({iduser : {type : String}}).
var member = new members({iduser : req.session.user._id})
by the way I have more than one member with the same iduser. and I wanna to find them by index. member.findOne({iduser})[0].
I use nodejs for implementation.
Every MongoDb Documents have a ObjectId like "612753311aafd14844ec4933"
so You Can find same IdUser with Object Id
member.findOne({_id : "OBJECT_ID", idUser :req.session.user._id })

Mongoose query for ID using an array

I want to query MongoDB using Mongoose with an array of objectIDs. I am not sure how to do this and also get back the 'name' property that is on the root of each document. I've looked online and can't seem to get it working. Below are two things I have tried that might be close but don't work.
{ _id: {
$in : ['5d193a4826540f7a89757f1d']
}
}
{ "name" : {
id: {
$in : ['5d193a4826540f7a89757f1d', '5d8c104d0f867b753d1f506c']
}
}}
First make ObjectIds from your strings:
const ids = ['5d193a4826540f7a89757f1d', '5d8c104d0f867b753d1f506c'];
const queryIds = ids.map(item => ObjectId(item));
Then find needed documents of your collection and set name: 1 to get only name (and _id by default):
collection.find({"_id": {$in : queryIds}}, {name: 1});

How to define a model & method in mongoose midleware?

I'm a newbie in mongodb and nodejs. I create a schema such as :
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ContactSchema = new Schema({
name : String,
email: String,
number : String
});
ContactSchema.methods.selectAll = function (callback){
console.log("I got list contact");
ContactModel.find({}).exec(function(err,items){
if(err)
console.error(err.stack);
else{
var notify = {
'message' : 'select all document successfully',
'data' : items,
'status' : 1
};
console.log(notify);
callback();
};
});
};
var ContactModel = mongoose.model('contactlist',ContactSchema);
module.exports = ContactModel;
Assume that I have connected to database with 'mongodb://localhost:27017/contactlist'. It has a database name contactlist, a collection contactlist with some documents
> db.contactlist.find({})
{ "_id" : ObjectId("576e8ac6d68807e6244f3cdb"), "name" : "Tome", "email" : "Tome#gmail.com", "number" : "333-333-333" }
{ "_id" : ObjectId("576e8b4fd68807e6244f3cdc"), "name" : "Trace", "email" : "Trace#gmail.com", "number" : "444-444-444" }
{ "_id" : ObjectId("576e8b4fd68807e6244f3cdd"), "name" : "Tuker", "email" : "Tuker#gmail.com", "number" : "555-444-777" }
>
My Question:
What does exactly 'ContactModel' in mongoose.model('ContactModel',ContactSchema); stand for? It is a name self-define or exactly name of collection in db?
I want to create a method for model ( crud task )
ContactSchema.methods.selectAll = function (){
// code here
}
This method can select all documents of a collection in mongo but my ContactModel.find function return null items.
$ node server
development server is running at 127.0.0.1 port 3000
I got list contact
{ message: 'select all document successfully',
data: [],
status: 1 }
undefined
I mean when I use find api of mongoose. How to do that?
Glad you already had solved your problem somehow. But this is just to address the root cause of problem the problem you faced. Hoping other find it helpful.
I think you have created a database named contactlist and a collection named contactlist before mongoose did it. And mongoose tries to be smart and puts the collection name as the name of model's pluralize (lib/npm source code reference and all the relevant rules are defined in this file). In your case it might have created a collection named contactlists
Although there is options for you to explicitly name your collection when creating a model by passing it as the third parameter to model (the way you did it) :
var ContactSchema = new Schema({ name : String /* , ..... */ },{collection : 'contactlist'});
This behavior is clearly documented in mongoose model API reference:
When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.
I resloved my problem. We have to map us with collection by
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ContactSchema = new Schema({
name : String,
email: String,
number : String
},{collection : 'contactlist'});
I worked!

Defining a map with ObjectId key and array of strings as value in mongoose schema

I'm facing a problem while creating Mongoose schema for my DB. I want to create a map with a objectId as key and an array of string values as its value. The closest that I can get is:
var schema = new Schema({
map: [{myId: {type:mongoose.Schema.Types.ObjectId, ref: 'MyOtherCollection'}, values: [String]}]
});
But somehow this is not working for me. When I perform an update with {upsert: true}, it is not correctly populating the key: value in the map. In fact, I'm not even sure if I have declared the schema correctly.
Can anyone tell me if the schema is correct ? Also, How can I perform an update with {upsert: true} for this schema?
Also, if above is not correct and can;t be achieved then how can I model my requirement by some other way. My use case is I want to keep a list of values for a given objectId. I don't want any duplicates entries with same key, that's why picked map.
Please suggest if the approach is correct or should this be modelled some other way?
Update:
Based on the answer by #phillee and this, I'm just wondering can we modify the schema mentioned in the accepted answer of the mentioned thread like this:
{
"_id" : ObjectId("4f9519d6684c8b1c9e72e367"),
... // other fields
"myId" : {
"4f9519d6684c8b1c9e73e367" : ["a","b","c"],
"4f9519d6684c8b1c9e73e369" : ["a","b"]
}
}
Schema will be something like:
var schema = new Schema({
myId: {String: [String]}
});
If yes, how can I change my { upsert:true } condition accordingly ? Also, complexity wise will it be more simpler/complex compared to the original schema mentioned in the thread?
I'd suggest changing the schema so you have one entry per myId,
var schema = new Schema({
myId : {type:mongoose.Schema.Types.ObjectId, ref: 'MyOtherCollection'},
values : [String]
})
If you want to update/upsert values,
Model.update({ myId : myId }, { $set : { values : newValues } }, { upsert : true })

Not able to remove document from mongo in Node

I'm trying to remove a document from a mongo database using Node. Is something wrong with my .remove method here:
deleteApplicant : function(req,res){
applicationModel.remove({_id:req.params.id} , function(err,count){
res.redirect('/applicants');
console.log(count)
})
}
Am I using the correct syntax?
_id in the database is probably of type ObjectId, but you're passing a string to the query.
Try this instead:
var ObjectId = require('mongodb').ObjectID;
...
applicationModel.remove({ _id : ObjectId(req.params.id) }, ...)

Resources