【问题标题】:Mongoose Saved _id'ss as a string instead of ObjectIdMongoose 将 _id'ss 保存为字符串而不是 ObjectId
【发布时间】:2015-12-13 16:41:13
【问题描述】:

在 Mongodb 和 Mongoose 中使用 Nodejs。

我刚刚发现 Mongoose/Mongodb 一直将自动生成的 _id 字段保存为字符串,而不是 ObjectId。 Mongodb shell 输出和示例文档:

> 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(字符串)来自此代码:

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) 来自此代码:

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 身份验证策略

更新:这是我的用户架构:

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,这给我带来了问题:

        ApiUser.findById(req.body.friend,{name:1},function(err,user) {
            console.log(user);
        })  

这将返回 null,除非我搜索具有正确 _id 的 2 个用户之一。 Req.body.friend 是_id,它是一个字符串。如何将所有文档的 _id 更改为 ObjectId,或使用字符串 _id 查询现有文档?

【问题讨论】:

  • 请显示您的架构和示例文档。并且请列出 mongodb shell 中显示的示例文档,而不是节点控制台输出,因为前者会正确显示类型信息。
  • 已发布架构和示例文档。另外,我道歉。输出来自 MongoDB shell。
  • 这里最合乎逻辑的情况是架构已更改或其他代码是导致此问题的原因。 Mongoose 需要两个特定设置才能以任何方式写入字符串,当然不是将 ObjectId 作为字符串。您应该能够通过一些简单的脚本将字符串值转换为ObjectId。如果有任何代码这样做,那不是您指向的代码。
  • 感谢您的帮助!我弄清楚了这个问题。如果您好奇,请在下面发布
  • 把这个作为字符串有什么问题吗?

标签: node.js mongodb mongoose


【解决方案1】:

这是一个非常具体的问题,但如果有人碰巧遇到类似问题,我的问题是我编写了一个文件,其中包含我的所有文档作为 json,以便在远程服务器上使用 mongoimport。

问题在于 JSON.stringify() 会将 objectId 转换为字符串。为了解决这个问题,我只写了一个小脚本来循环遍历用户数组中的所有对象,并使用以下命令将所有 _id 转换回 objectId:

var mongoose = require('mongoose');
user._id = mongoose.Types.ObjectId(users[i]._id);

然后在我的猫鼬模型上调用 Model.create() 并使用更新的文档批量插入,并删除原始文档

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2019-06-23
    • 2020-12-03
    • 2021-03-27
    • 2015-01-17
    • 2014-07-30
    • 2017-05-20
    • 2019-07-12
    • 2012-03-18
    相关资源
    最近更新 更多