Mongoose:从现有数据生成架构

wil*_*ibi 7 mongoose mongodb node.js

例如,我user在db中有集合:

{'_id':0, 'name': 'Joe', 'score':[80, 33]}
{'_id':1, 'name': 'Moe', 'score':[90, 81]}
... ...
Run Code Online (Sandbox Code Playgroud)

如何使用现有格式读取此数据,这意味着,使用现有架构而不创建新架构.

我读了Mongoose doc并用google搜索了一段时间但没有找到满意的答案.

tpa*_*pae 7

如果您制作具有相同架构的模型,它将起作用。

var schema = new mongoose.Schema({ name: 'string', score: [] });
var user = mongoose.model('User', schema);
Run Code Online (Sandbox Code Playgroud)

编辑:

Mongoose 是一个 ODM,因此您需要一个架构来创建对象。如果您需要运行查询并从数据库中获取原始数据,我会坚持使用这个库:

https://github.com/mongodb/node-mongodb-native

  • 我的意思是有没有办法读取已经存在的数据,然后从现有数据的模式中生成模式。 (2认同)

idk*_*kjs 5

在现有集合中使用猫鼬时,必须在猫鼬模式中引用该集合。这样做的方法是将集合的名称添加到您的架构。因此,如果您的集合位于“ mongodb:// localhost:27017 / test”中并称为“事物”,则可以使用:

~~~
const Schema = mongoose.Schema;
const ThingSchema = new Schema({
  name: {
    type: String
  }
});

const Model = mongoose.model('Thing', ThingSchema, 'things');
module.exports = Model;
~~~
Run Code Online (Sandbox Code Playgroud)

感谢http://chrisflx.blogspot.fr/2014/04/nodejs-mongoose-with-preexisting-data.html?m=1