node.js - Mongoose 将 _id'ss 保存为字符串而不是 ObjectId

标签 node.js mongodb mongoose

将 Nodejs 与 Mongodb 和 Mongoose 结合使用。

我刚刚发现 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's (ObjectId's) 来自这段代码:

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 查询现有文档?

最佳答案

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

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

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

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

关于node.js - Mongoose 将 _id'ss 保存为字符串而不是 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32619699/

相关文章:

node.js - 使用 Typescript 在 Mongoose 中链接 ES6 Promise

mongodb - Mongoose 查找结果,然后用 findOne 替换字段

javascript - 异步函数总是返回 undefined

node.js - 在 MongoDB 中使用 like 查询

sql - MongoDB 查询组合和 & 或

ruby - MongoDB + ruby 。如何访问文档属性?

node.js - TypeError : Cannot read property 'ref' of undefined | Express

javascript - 如何在 Node.js 智能感知中启用 Jasmine 支持

node.js - 如何使用 bitgo 发送 xrp 代币

node.js - 更新后的 npm 问题