My schema is:
var VenueSchema = new Schema({
_id: Schema.Types.ObjectId
,rating : Number
})
And I am trying:
var v = new Venue()
v.name = venue.name
Venue.update({ id : Schema.Types.ObjectId(venue.id)}, v, {upsert: true})
But there is nothing in the DB. Where am I wrong?
You need to use _id instead of id and a plain JS object in the update call, and Mongoose will do the ObjectId casting for you. Try this instead:
Venue.update({ _id : venue.id}, {name: venue.name}, {upsert: true});
Note that name doesn't appear in your schema, which probably isn't what you want.
Related
I have a collection with the following document
{_id:'12345',account:{ba:0,br:0,ac:0}, scores:{a:0,b:0}}
I have a resolver and after running it
const input = {account:{ba:1,br:2,ac:3}, scores:{a:1,b:1}}
const profileId='12345'
const res = await modelProfile.findOneAndUpdate({ _id: profileId }, input);
it finds the document and properly changes it but it is adding also _id to each object there :
{_id:'12345',account:{_id:'46456',ba:1,br:2,ac:3}, scores:{_id:'4645677', a:1,b:1}}
How can I prevent mongoose from automatically adding _id to the SUBDOCUMENT objects of the document that they don't have ObjectId already. (as you saw, the document has ObjectId but objects inside as subdocuments does not have it)
I found the solution, I should change schema
var subSchema = mongoose.Schema({
// your subschema content
}, { _id : false });
Let's say I have a simple mongoose schema like this
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String;
age: String,
created: { type: Date, default: Date.now }
})
module.exports = mongoose.model('User', UserSchema);
I can easily find all User collections with User.find({}). But I want to find only specified collections by their _id.
For example I have 10 user collections, and want to find only users according their Id in this dynamic array
["5b66c0868278664f0d2f2fec","5b66c5a947eaed565b694efa"]
so I am required to use where or match?
did you try $in?
User.find({_id : {$in : ["5b66c0868278664f0d2f2fec","5b66c5a947eaed565b694efa"]})
The $in operator selects the documents where the value of a field
equals any value in the specified array. To specify an $in expression,
use the following prototype:
User.find({ _id: { $in: ["5b66577c2f05bf1eb07956e0" ,"5b66b1879526eb0444d047cb"] }})
.then(users =>{
console.log("user", users)
})
Pass user id in postman parameter, then assign it to a variable then pass it to the function which is written for db activities. Then modal.findone(id);
Using Mongoose in NodeJS I'm able to create a database and insert data and find the data when using mongoose, however when I use the mongo shell with show dbs command it shows the database but the size of the database constantly remains at 0. Is there something I'm missing? Here's my code
mongoose = require('mongoose');
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/dt');
var UserSchema = new Schema({
first_name: String,
last_name: String
});
var users = mongoose.model('Users',UserSchema);
var new_user = new users({ first_name: "firstname",
last_name: "lastname" });
new_user.save(function(err) {
if(err) return;
else console.log("saved");
});
users.find({first_name:'firstname'}).exec(function(err,data) {
console.log(data);
});
you might need to use the insert() method
e.g
db.detail.insert(
{
"data" : {
"name" : "any_name",
"zipcode" : "10075",
},
}
)
After which you can use the find() method returns query results in a cursor, which is an iterable object that yields documents.
You can read more from Insert a Document and Find or Query Data with the mongo Shell
I am trying to create a schema.
I keep getting the document does not have an _id error, besides the code below I did try to initialize it explicitly, but nothing works.
var UserSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
var User = mongoose.model('user', UserSchema);
http://mongoosejs.com/docs/guide.html#_id reads:
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor.
If you explicitly define _id type in the schema, it's your responsibility to set it:
User._id = mongoose.Types.ObjectId('000000000000000000000001');
_id is the primary key for document in a mongoDB. You don't have to specify the _id in your Schema. It will be added automatically once the document is created.
Here is the sample code:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
username: {
type: String
},
password: {
type: String
}
});
module.exports = mongoose.model('User', User);
I think you dont need to define the _id. Try without and see if it works.
Also if that is not the problem try this:
_id: { type: Mongoose.Schema.Types.ObjectId }
if you want to define _id in your schema explicity you should assign a value to "_id" for each insertation. you have two way to solve this problem :
1. remove "_id" from your schema and mongoose generate id automatically.
2. assign a value to _id :
var ObjectId = require('mongodb').ObjectID; // or var ObjectId = require('mongoose').Types.ObjectId; "but the first worked for me"
User._id = objectId('1111111111111111111');
simple remove the line from your code
_id: mongoose.Schema.ObjectId
Allora, I'm using mongoose for the first time and I decided to create 2 schemes: the first one represents a user and the second one represents his enquires. Users have an array of enquires like:
var userSchema = new mongoose.Schema({
name: String,
enquires: { type : [Enquire.schema] , "default" : [] },
});
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
I see that if I search for an enquire and update its status, it doesn't update the same enquire on the user's array, meaning that they are different object. I don't want to save an array of IDs as it will be the same as a relational database, so I see only 1 solution which is forgetting about the enquire scheme and use only the User scheme. Is it the way mongoose works? For every relationship do I have to insert everything like nested object?
I think you should use references to achieve what you want to achieve.
For more information on mongoose references and populate see Mongoose Populate documentation.
Try this, It may help you.
User Schema :
var userSchema = new mongoose.Schema({
name: String,
enquires: [{ type : mongoose.Schema.Types.ObjectId , ref : 'Enquiry' }]//array of enquiries
});
var User = mongoose.model('User',userSchema );
module.exports = User;
Enquiry Schema :
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
var Enquiry = mongoose.model('Enquiry',enquireSchema );
module.exports = Enquiry ;
Working :
create a new Enquiry.
Push it's ID(_id) into user's enquires array.
var enquiry = new Enquiry();
enquiry.enquire = "Dummy enquiry";//set the enquiry
enquiry.save(function(err,result){
if(!err){
//push 'result._id' into users enquires array
}
});
whenever you update an enquiry, it will be automatically updated in
user's document.
use populate to retrieve user's enquiries.
You can embed sub documents (entity) which has id and is like a document or embed native array like a normal property.
And I think the correct definition for yours is :
var enquireSchema = new mongoose.Schema({
status: {type: String, 'default': 'pending'},
enquire: String,
});
var userSchema = new mongoose.Schema({
name: String,
enquires: { type : [enquireSchema] , "default" : [] },
});
If you use refs in embedded link then there are two separate collections and be like relational db's.