相关疑难解决方法(0)

如何使用mongoose生成ObjectId?

我想ObjectId用Mongoose 生成一个MongoDB .有没有办法ObjectId从Mongoose 访问构造函数?

  • 这个问题是关于从头开始生成新的 ObjectId.生成的ID是全新的通用唯一ID.

  • 另一个问题是关于ObjectId现有字符串表示创建一个.在这种情况下,您已经有一个ID的字符串表示 - 它可能是也可能不是普遍唯一的 - 并且您正在将其解析为ObjectId.

mongoose mongodb node.js

113
推荐指数
4
解决办法
10万
查看次数

Mongoose String to ObjectID

我有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);
Run Code Online (Sandbox Code Playgroud)

我如何使用它:

let comment = new commentsModel;
str = 'Here my ObjectId code' //
comment.user_id = str;
comment.post = str;
comment.save();
Run Code Online (Sandbox Code Playgroud)

当我创建"注释"模型并分配字符串user_id值或发布时,我在保存时出错.我将console.log(comment)所有数据分配给变量.

我尝试:

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

当然,我还包括猫鼬BEFORE ALL CALLS

import * as mongoose from 'mongoose';
Run Code Online (Sandbox Code Playgroud)

什么都行不通

mongoose mongodb node.js

10
推荐指数
2
解决办法
2万
查看次数

Mongoose 不会增加数字字段

我正在使用 MongoDB 和猫鼬。我目前有一个like按钮,当我单击它时,我想增加文档中的“喜欢”字段。目前我的文档具有以下架构:

brote {
  name: 
  content:
  created: 
  likes: 
} 
Run Code Online (Sandbox Code Playgroud)

并且我已经测试过我的查询中的 ID 与我的数据库中的对象的 ID 相匹配。

我咨询了如何在 Mongoose 中增加 Number 值?用猫鼬增加值?但这些解决方案似乎没有对我的数据库进行任何更改。也许有一些显而易见的东西我失踪了?

索引.js

mongoose.connect('mongodb://localhost:27017/bromies', { useUnifiedTopology: true, useNewUrlParser: true });
mongoose.set('useFindAndModify', false);
var Brote = mongoose.model('Brote', broteFormSchema);

app.post('/likes', (req, res) => {
    let query = { id: req.body._id};
    Brote.findOneAndUpdate(query, {$inc: { 'likes': 1 }});

  })
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js express

1
推荐指数
1
解决办法
915
查看次数

标签 统计

mongodb ×3

mongoose ×3

node.js ×3

express ×1