【问题标题】:Mongoose String to ObjectID猫鼬字符串到 ObjectID
【发布时间】:2016-11-21 15:06:12
【问题描述】:

我有一个带有 ObjectId 的字符串。

var comments = new Schema({
    user_id:  { type: Schema.Types.ObjectId, ref: 'users',required: [true,'No user id found']},
    post: { type: Schema.Types.ObjectId, ref: 'posts',required: [true,'No post id found']}....

export let commentsModel: mongoose.Model<any> = mongoose.model("comments", comments);

我是如何使用它的:

let comment = new commentsModel;
str = 'Here my ObjectId code' //
comment.user_id = str;
comment.post = str;
comment.save();

当我创建“评论”模型并分配字符串 user_id 值或发布时,我在保存时出错。我把console.log(comment) 的所有数据都分配给了vars。

我试试:

 var str = '578df3efb618f5141202a196';
    mongoose.mongo.BSONPure.ObjectID.fromHexString(str);//1
    mongoose.mongo.Schema.ObjectId(str);//2
    mongoose.Types.ObjectId(str);//3
  1. TypeError: 对象函数 ObjectID(id) {
  2. TypeError:无法调用未定义的方法“ObjectId”
  3. TypeError:无法读取未定义的属性“ObjectId”

当然我也包括了猫鼬在所有呼叫之前

import * as mongoose from 'mongoose';

没有任何作用。

【问题讨论】:

  • 该问题中没有任何方法有帮助(
  • 然后开始显示一些代码/错误消息,这些消息应该从一开始就包含在您的问题中。当您不显示失败的原因(您的代码)以及失败的原因(错误)时,我们无法为您提供帮助
  • 我展示了字符串的代码和示例

标签: node.js mongodb mongoose


【解决方案1】:

使用这个

 var mongoose = require('mongoose');
 var str = '578df3efb618f5141202a196';
 var mongoObjectId = mongoose.Types.ObjectId(str);

【讨论】:

    【解决方案2】:

    您想使用默认导出:

    import mongoose from 'mongoose';
    

    之后,mongoose.Types.ObjectId 将起作用:

    import mongoose from 'mongoose';
    console.log( mongoose.Types.ObjectId('578df3efb618f5141202a196') );
    

    编辑: 完整示例(使用mongoose@4.5.5 测试):

    import mongoose from 'mongoose';
    
    mongoose.connect('mongodb://localhost/test');
    
    const Schema = mongoose.Schema;
    
    var comments = new Schema({
        user_id:  { type: Schema.Types.ObjectId, ref: 'users',required: [true,'No user id found']},
        post: { type: Schema.Types.ObjectId, ref: 'posts',required: [true,'No post id found']}
    });
    
    const commentsModel = mongoose.model("comments", comments);
    
    let comment = new commentsModel;
    let str = '578df3efb618f5141202a196';
    comment.user_id = str;
    comment.post = str;
    comment.save().then(() => console.log('saved'))
                  .catch(e => console.log('Error', e));
    

    数据库显示:

    mb:test$ db.comments.find().pretty()
    {
        "_id" : ObjectId("578e5cbd5b080fbfb7bed3d0"),
        "post" : ObjectId("578df3efb618f5141202a196"),
        "user_id" : ObjectId("578df3efb618f5141202a196"),
        "__v" : 0
    }
    

    【讨论】:

    • 当我创建“cmets”模型并设置值时出现错误。 comments.user_id = mongoose.Types.ObjectId('578df3efb618f5141202a196');message: 'Cast to ObjectId failed for value "" at path "user_id"', name: 'CastError', type: 'ObjectId', value: '', path: 'user_id'Mongoose 看到空场... ((((
    • 这是一个不同的问题(尽管comments 是您的示例代码中的一个模式,但您将它用作文档?)。您能否展示如何从架构创建模型、如何创建文档以及如何将 user_id 分配给它(全部通过编辑您的问题)?
    • 为问题添加一些细节
    • @Melixion comments 是一个模式,所以 new comments 应该已经失败了。它看起来不像您正在使用的实际代码。
    • @AlecDonaldMather 实际上,它必须是 ObjectId 的有效字符串表示形式:D
    猜你喜欢
    • 2013-03-24
    • 2020-10-25
    • 2021-01-08
    • 2017-04-06
    • 2020-07-25
    • 2016-01-01
    • 2016-11-06
    • 1970-01-01
    • 2019-10-07
    相关资源
    最近更新 更多