标签: mongoose

Mongoose填充包含ref的对象数组

我有一个Mongoose模式,lists其中包含一个对象数组,这些对象包含对另一个集合的引用和嵌套的数字数组:

var Schema, exports, mongoose, schema;

mongoose = require("mongoose");

Schema = mongoose.Schema;

schema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  lists: [
    {
      list: {
        type: Schema.ObjectId,
        require: true,
        ref: "List"
      },
      allocations: [
        {
          type: Number,
          required: true
        }
      ]
    }
  ],
  createdAt: {
    type: Date,
    "default": Date.now
  },
  updatedAt: {
    type: Date
  }
});

exports = module.exports = mongoose.model("Portfolio", schema);
Run Code Online (Sandbox Code Playgroud)

但是,如果没有得到,我就无法populate按预期工作TypeError: Cannot read property 'ref' of …

mongoose

52
推荐指数
3
解决办法
6万
查看次数

Mongoose:CastError:对于路径"_id"的值"[object Object]",转换为ObjectId失败

我是node.js的新手,所以我有一种感觉,这将是我所忽略的愚蠢,但我找不到能够解决问题的答案.我要做的是创建一个路径,创建一个新的子对象,将其添加到父的子数组,然后将子对象返回给请求者.我遇到的问题是,如果我将字符串id传递给findById,节点崩溃了

TypeError:Object {}没有方法'cast'

如果我尝试传入ObjectId,我会得到

CastError:对于路径"_id"处的值"[object Object]",转换为ObjectId失败

这是我的代码的大致轮廓:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId; //Have also tried Schema.Types.ObjectId, mongoose.ObjectId

mongoose.connect('mongodb://user:password@server:port/database');

app.get('/myClass/:Id/childClass/create', function(request, result) {
  var id = new ObjectId(request.params.Id);
  MyClass.findById(id).exec( function(err, myClass) {
    if (err || !myClass) { result.send("error: " + err + "<br>" + JSON.stringify(id) || ("object '" + request.params.Id + "' not found: " + id)); return; }
    var child = ChildClass();
    myClass.Children.addToSet(child);
    myClass.save();
    result.send(child);
  });
});
Run Code Online (Sandbox Code Playgroud)

如果我使用路径"/ myClass/51c35e5ced18cb901d000001/childClass/create"执行此代码,则这是代码的输出:

错误:CastError:对于路径"_id"{"path":"51c35e5ced18cb901d000001","instance":"ObjectID","validators":[],"setters":的值"[object Object]",Cast to ObjectId失败], …

mongoose mongodb node.js

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

如何设置useMongoClient(Mongoose 4.11.0)?

这是我用来连接数据库的代码:

private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
    return Mongoose.connect(databaseUri).then(() => {
        debug('Connected to MongoDB at %O', databaseUri);
        return Mongoose.connection;
    });
}
Run Code Online (Sandbox Code Playgroud)

今天我将Mongoose更新到4.11.0版本,运行我的测试时收到了这个警告:

(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`
Run Code Online (Sandbox Code Playgroud)

我找不到任何关于如何"设置useMongoClient"的信息.

你们知道怎么样吗?

mongoose mongodb node.js

52
推荐指数
6
解决办法
4万
查看次数

如何使用Node.js,Express和Mongoose进行身份验证?

我使用nodejs + express制作了简单的nodejs应用程序.现在我想让用户认证.我想通过使用mongoose实现会话处理.你能举个例子吗?

authentication mongoose node.js express

51
推荐指数
3
解决办法
7万
查看次数

如何获取在另一个模型中定义的mongoose数据库的Schema

这是我的文件夹结构:

+-- express_example
|---- app.js
|---- models
|-------- songs.js
|-------- albums.js
|---- and another files of expressjs
Run Code Online (Sandbox Code Playgroud)

我在文件songs.js中的代码

var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;

var SongSchema = new Schema({
name: {type: String, default: 'songname'}
, link: {type: String, default: './data/train.mp3'}
, date: {type: Date, default: Date.now()}
, position: {type: Number, default: 0}
, weekOnChart: {type: Number, default: 0}
, listend: {type: Number, default: 0}
});

module.exports = mongoose.model('Song', SongSchema);
Run Code Online (Sandbox Code Playgroud)

这是我的文件albums.js中的代码

var mongoose = require('mongoose') …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose mongodb nosql node.js

51
推荐指数
3
解决办法
5万
查看次数

在单独的模块中定义Mongoose模型

我想在一个单独的文件中分离我的Mongoose模型.我试图这样做:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var Material = new Schema({
    name                :    {type: String, index: true},
    id                  :    ObjectId,
    materialId          :    String,
    surcharge           :    String,
    colors              :    {
        colorName       :    String,
        colorId         :    String,
        surcharge       :    Number
    }
});

var SeatCover = new Schema({
    ItemName            :    {type: String, index: true},
    ItemId              :    ObjectId,
    Pattern             :    String,
    Categories          :    {
        year            :    {type: Number, index: true},
        make            :    {type: String, index: true},
        model …
Run Code Online (Sandbox Code Playgroud)

mongoose node.js express

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

Mongoose删除文件中的数组元素并保存

我的模型文档中有一个数组.我想根据我提供的密钥删除该数组中的元素,然后更新MongoDB.这可能吗?

这是我的尝试:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var favorite = new Schema({
    cn: String,
    favorites: Array
});

module.exports = mongoose.model('Favorite', favorite, 'favorite');

exports.deleteFavorite = function (req, res, next) {
    if (req.params.callback !== null) {
        res.contentType = 'application/javascript';
    }
    Favorite.find({cn: req.params.name}, function (error, docs) {
        var records = {'records': docs};
        if (error) {
            process.stderr.write(error);
        }
        docs[0]._doc.favorites.remove({uid: req.params.deleteUid});

        Favorite.save(function (error, docs) {
            var records = {'records': docs};
            if (error) {
                process.stderr.write(error);
            }
            res.send(records);

            return next();
        });
    });
};
Run Code Online (Sandbox Code Playgroud)

到目前为止,它找到了文档,但删除或保存工作.

mongoose node.js

51
推荐指数
4
解决办法
8万
查看次数

猫鼬:如何定义一个独特的字段组合?

如果我有这样的架构:

var person = new Schema({
  firstName:  String,
  lastName: String,
});
Run Code Online (Sandbox Code Playgroud)

我想确保只有一个文件具有相同的firstName和lastName.

我怎么能做到这一点?

mongoose

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

Mongoose.js:如何实现创建或更新?

我有一个请求,其中包含数据和_id

如果带有_id的记录存在并且创建一个没有人的代码,那么实现代码的更好方法是什么?我的代码:

var obj = req.body;
Model.findById(obj._id, function(err, data){
    if (!data){
        var model = new Model(obj)
        model.save(function(err, data){
            res.send({method: 'create', error: err, data: data})
        })
    } else {
        Model.findByIdAndUpdate(obj._id, obj, function(){
            res.send({method: 'update', error: err, data: data})
        })
    }
Run Code Online (Sandbox Code Playgroud)

我只是想也许有更好的办法.

mongoose

50
推荐指数
1
解决办法
4万
查看次数

Mongoose - 如果不存在则创建文档,否则,在任何一种情况下都更新 - 返回文档

我正在寻找一种方法来重构我的部分代码,使其更短更简单,但我不太了解Mongoose,我不知道如何继续.

我正在尝试检查一个集合是否存在文档,如果它不存在,则创建它.如果确实存在,我需要更新它.在任何一种情况下,我都需要访问文档的内容.

到目前为止我设法做的是查询特定文档的集合,如果找不到,则创建一个新文档.如果找到它,我会更新它(当前使用日期作为虚拟数据).从那里我可以访问我的初始find操作中找到的文档或新保存的文档,这可行,但必须有一个更好的方法来完成我所追求的.

这是我的工作代码,没有分散注意力.

var query = Model.find({
    /* query */
}).lean().limit(1);

// Find the document
query.exec(function(error, result) {
    if (error) { throw error; }
    // If the document doesn't exist
    if (!result.length) {
        // Create a new one
        var model = new Model(); //use the defaults in the schema
        model.save(function(error) {
            if (error) { throw error; }
            // do something with the document here
        });
    }
    // If the document does exist
    else {
        // Update it …
Run Code Online (Sandbox Code Playgroud)

javascript refactoring mongoose node.js

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