猫鼬将_id保存为字符串而不是ObjectId
将Nodejs与Mongodb和Mongoose结合使用.
Using Nodejs with Mongodb and Mongoose.
我刚刚发现Mongoose/Mongodb一直将自动生成的_id字段保存为字符串,而不是ObjectId. Mongodb Shell输出和示例文档:
I just found out that Mongoose/Mongodb has been saving the auto generated _id field as a string as opposed to an ObjectId. Mongodb shell output and sample documents:
> db.users.count({_id: {$type: 7}})
2
> db.users.count({_id: {$type: 2}})
4266
> db.users.find({_id: {$type: 7}},{_id:1}).limit(1)
{ "_id" : ObjectId("55f7df6fdb8aa078465ec6ec") }
> db.users.find({_id: {$type: 2}},{_id:1}).limit(1)
{ "_id" : "558c3472c8ec50de6e560ecd" }
4266 _id的(字符串)来自以下代码:
The 4266 _id's (strings) come from this code:
var newUser = new ApiUser();
newUser.name = name;
newUser.link = link;
newUser.signupTime = new Date().getTime();
newUser.initialBrowser = initialBrowser;
newUser.save(function(err) {
if (err)
res.json(err);
else
res.json('success');
});
和2个_id(ObjectId)来自此代码:
and the 2 _id's (ObjectId's) come from this code:
var newUser = new User();
newUser.facebook.id = profile.id;
newUser.facebook.token = token;
newUser.name = profile.name.givenName + ' ' + profile.name.familyName;
if (profile.emails) {
newUser.facebook.email = (profile.emails[0].value || '').toLowerCase();
}
newUser.facebook.gender = profile.gender;
newUser.facebook.profilePic = profile.photos[0].value;
newUser.save(function(err) {
if (err)
return done(err);
return done(null, newUser);
});
User()和ApiUser()都引用相同的模型.保存ObjectId的对象是使用Passport.js的Facebook身份验证策略
User() and ApiUser() both reference the same model. The one that saves ObjectId's is in a Facebook authentication Strategy with Passport.js
更新:这是我的用户架构:
UPDATE: here is my user schema:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
// define the schema for our user model
var userSchema = Schema({
name: String,
email: String,
link: Number,
location: String,
residence: String,
age: Number,
gender: String,
subject: String,
signupTime: Number,
finishTime: Number,
shared: String,
search: String,
shareFriend: String,
local : {
email : String,
password : String
},
facebook : {
id : String,
token : String,
email : String,
name : String,
gender : String,
profilePic : String
},
interestsSummary: [Number],
interests: [{name: String, iType: String}],
valuesSummary: [Number],
values: [{name: String}],
traitsSummary: [Number],
traits: [{name: String}],
bio: String,
friendInterests: Number,
friendValues: Number,
friendPersonality: Number,
surveyLength: String,
missedInfo: String,
anythingElse: String,
finalBrowser: String,
consented: Boolean
}, {collection: "users"});
// generating a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
问题是我似乎无法基于字符串查询mongodb,这给我带来了问题:
The issue is that I can't seem to query mongodb based on the ones that are strings, which is giving me problems:
ApiUser.findById(req.body.friend,{name:1},function(err,user) {
console.log(user);
})
这将返回null,除非我搜索具有正确_id的2个用户之一. Req.body.friend是_id,它是一个字符串.如何将所有文档的_id更改为ObjectId,或使用字符串_id来查询现有文档?
This returns null unless I search for one of the 2 users with a proper _id. Req.body.friend is the _id, which is a string. How can I either change all the document's _id's to ObjectId's, or query the existing documents with string _id's?
这是一个非常具体的问题,但是如果有人碰巧遇到类似的问题,我的问题是我写了一个文件,其中所有文档都作为json在远程服务器上使用mongoimport.
This is a pretty specific question, but if anyone happens to stumble upon a similar issue, my problem was that I wrote a file with all my documents as a json to use mongoimport on a remote server.
问题是JSON.stringify()会将objectId转换为字符串.为了解决这个问题,我写了一个小脚本来遍历我的用户数组中的所有对象,并使用以下命令将所有_id返回到objectId:
The issue was that JSON.stringify() will convert an objectId to a string. To fix it I wrote just wrote a small script to loop through all the objects in my users array and convert all _id's back to objectId's with the following command:
var mongoose = require('mongoose');
user._id = mongoose.Types.ObjectId(users[i]._id);
然后在猫鼬模型上调用Model.create(),将更新后的文档批量插入,并删除原始文档
Then calling Model.create() on my mongoose model with the updated documents to bulk insert, and deleted the original documents